简体   繁体   English

TypeScript For循环访问嵌套数组

[英]Typescript For Loop access nested array

I'm having issues access a value in a nested array. 我在访问嵌套数组中的值时遇到问题。 I have a json object that looks like 我有一个看起来像的json对象

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中的键4?

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         
  }

}

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)); }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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