Reputation: 57
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)
Upvotes: 0
Views: 41
Reputation: 1459
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"]
Upvotes: 0
Reputation: 386
You can access the snack with an itemName of "chocolate" like so:
const chocolate = nestedData.innerData.snacks[1].itemName;
Upvotes: 2