简体   繁体   中英

How do I access a particular value from a nested array within object?

this is the object structure. i am trying to get the value chocolate.

var nestedData = {
  innerData: {
    order: ["first", "second", "third"],
    snacks: [
      { item: "chips", cost: 20 },
      { itemName: "chocolate", cost: 40 },
      { itemName: "fruits", cost: 80 }
    ],
    numberData: {
      primeNumbers: [2, 3, 5, 7, 11],
      fibonnaci: [1, 1, 2, 3, 5, 8, 13]
    }
  }
};


I have tried below but gives undefined


let x = nestedData.innerData["snacks"]["itemName"]
console.log(x)

You can access the snack with an itemName of "chocolate" like so:

const chocolate = nestedData.innerData.snacks[1].itemName;

The problem is that "snacks" is an array, not an object.

Just add the index and you should be all set.

nestedData.innerData["snacks"][1]["itemName"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM