Access values within an array from the index

Asked

Viewed 609 times

6

I have a variable x with the following content inside:

x = [ {
    id: '1',
    name: 'name,
} ]

And I thought to access the id were x.id, however, it is not so. How to access?

1 answer

6


There’s an object inside a array. First you access the element index (in case there is only one, then it is 0), then access the object member, as you did correctly.

var x = [{
  id: '1',
  name: 'name',
}]
console.log(x[0].id);

I put in the Github for future reference.

When assigning a value the brackets delimit a array. Keys delimit an object.

Just as curiosity would also work x[0]["id"] since in Javascript an object is actually a array associative.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.