Ninad Bondre
Ninad Bondre

Reputation: 57

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)

Upvotes: 0

Views: 41

Answers (2)

yohosuff
yohosuff

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

davidmwhynot
davidmwhynot

Reputation: 386

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

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

Upvotes: 2

Related Questions