gnxvw
gnxvw

Reputation: 454

How to get an element of array in state in React?

I have array in this.state.placeinfo, and I want to show id.

0:{
  id: "2"
  latitude: "35.737939"
  longitude: "139.7400265"
}

I code like this, but the result says undefined.

console.log(this.state.placeinfo.id)

...
const line = this.state.placeinfo
console.log(line.id)

Do you have any idea to show id?

Upvotes: 0

Views: 52

Answers (1)

user2340824
user2340824

Reputation: 2152

this.state.placeinfo contains an array of Objects. When you did

const line = this.state.placeinfo

line was actually an array, which doesn't have the ID property you are looking for. It's only when you get an element from within that array, will you have access to those properties.

So, if you wanted to get the ID of the first object, within the array it would be:

const line = this.state.placeinfo[0];

Then console.log(line.id) will work.

Upvotes: 3

Related Questions