0

I'm developing a webApp using React, I'm having issues accessing data inside a javascript Object, here is the code:

      const user_position = System.prototype.getUserPosition();

console.log({user_position:user_position,latitude:user_position.latitude,longitude:user_position["longitude"]})

        position_update.latitude = user_position.latitude;
        position_update.longitude = user_position.longitude;
        position_update.timestamp = user_position.timestamp

        this.setState({currentSearchSelection: "La tua posizione"});

I want to access the data inside the user_position Object, but the output is quite strange:

{user_position: {…}, latitude: undefined, longitude: undefined}
latitude: undefined
longitude: undefined
user_position:
latitude: 41.818550699999996
longitude: 12.495401099999999
timestamp: 1587660938111
__proto__: Object
__proto__: Object

Basically, the user_position is populated but I cannot access the values inside it, what I'm doing wrong?

1
  • 1
    do console.log("user_position:",user_position) to get a better look, or even console.log("keys:",Object.keys(user_position)) to see the keys inside. The object does seem to be defined but you can't see the details from your current log statement. Commented Apr 23, 2020 at 17:27

2 Answers 2

1

If you know the name of the exact values in the object, you can get it directly: console.log(user_position.object_name)

Right now it is saying that your user_position is an object, and is defined.

Maybe even try just print that user_object console.log(user_object) to see what is in it.

Sign up to request clarification or add additional context in comments.

Comments

0

Thanks everybody for the support, the answer was simple: the getUserPosition() method was async(even it was not marked as it), so there was nothing wrong in the code of this particular class, what happened was:

    user_position.object_name // print undefined since user_position is not populated

    user_position // print value because the variable is linked to the result of the async method

So what I did was editing the code with a callback:

System.prototype.getUserPosition().then(user_position=>{

        position_update.latitude = user_position.latitude;
        position_update.longitude = user_position.longitude;
        position_update.timestamp = user_position.timestamp

        this.setState({currentSearchSelection: "La tua posizione"});
})

and everything worked.

1 Comment

if previous answers was helpful you better upvote them

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.