Home > OS >  How to access key in Nested object in an array within a JSON file [duplicate]
How to access key in Nested object in an array within a JSON file [duplicate]

Time:09-16

var data = [
  {
    code: 42,
    items: [{
        id: 1,
        name: 'foo'
    }, {
        id: 2,
        name: 'bar'
    }]
  }];

console.log(data.items[0].name === 'foo');

I am trying to access the key and checking if the value are same then return true or false, I am getting an error while accessing it.

Data is an array. It should be data[0].items[0].name

var data = [
  {
    code: 42,
    items: [{
        id: 1,
        name: 'foo'
    }, {
        id: 2,
        name: 'bar'
    }]
  }];

console.log(data[0].items[0].name === 'foo');

CodePudding user response:

According to your data it should be like this

data[0].items[0].name === 'foo'

CodePudding user response:

Its data[0].items[0].name

  • data is an array.
  • items node in each node of data is also an array.

To access the zeroth node of data you have to use data[0] just same as you did with items

var data = [
  {
    code: 42,
    items: [{
        id: 1,
        name: 'foo'
    }, {
        id: 2,
        name: 'bar'
    }]
  }];

console.log(data[0].items[0].name === 'foo');

  • Related