0

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)
1
  • 3
    that's not a nested object, it's a nested array within a nested object. you need to get at the index. let x = nestedData.innerData["snacks"][1]["itemName"] Commented Apr 7, 2020 at 0:02

2 Answers 2

2

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

const chocolate = nestedData.innerData.snacks[1].itemName;
Sign up to request clarification or add additional context in comments.

Comments

0

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"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.