0

I'm having issues access a value in a nested array. I have a json object that looks like

let obj=
{
"key1":"value1",
"key2":"value2",,
"results":[
        {
            "key3":"value3",
            "array1":[],
            "array2":[
                {
                    "key4":"value4",
                    "key5":"value5",
                }
            ],
            "array3":[]
        }
    ]
}

I wrote a loop

for (let i = 0; i < obj.results.length; i++) {
console.log(obj.results[i].key3)
// this will return value3
}

How do I get the to key 4 in array 2?

2
  • 3
    obj.results[0].array2[0].key4 Commented Feb 16, 2018 at 16:23
  • wow, as simple as that. Thank you Commented Feb 16, 2018 at 16:29

2 Answers 2

1
for (let i = 0; i < obj.results.length; i++) {
  for (let j = 0; i < obj.results[i].array2.length; i++) {
     console.log(obj.results[i].array2[j].key4         
  }

}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you this is exactly what I was looking for and ending up implementing
0

Assuming that your data structure is this exact structure, then this code should work:

let obj = {
  "key1":"value1",
  "key2":"value2",
  "results":[
    {
      "key3":"value3",
      "array1":[],
      "array2":[
        {
          "key4":"value4",
          "key5":"value5",
        }
      ],
      "array3":[]
    }
  ]
};

const key4Values: Array<string> = obj.results.map((val) => {
  return [].concat.apply([], val.array2.map((arr2) => arr2.key4));
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.