gpt4 book ai didi

javascript - JSON 对象键值

转载 作者:行者123 更新时间:2023-11-30 08:03:45 24 4
gpt4 key购买 nike

这是我来自服务器的 JSON 响应

{    "responses": 
{
"army":[{"name":"jhon","age":"32"},{"name":"sam".....}]
"navy":[{"name":"tom","age":"42"},{"name":"josh"......}]
"air":[{"name":"jhona","age":"34"},{"name":"samy"........}]
}
}

我试过:

var obj1= myArrays.responses; 
for (var key1 in obj1) {
console.log(key1);
for (var i = 0; i < obj1.length; i++) {
console.log(obj1.length);
}
}

我希望输出看起来像这样,但我不知道该怎么做。

In army, jhon(age:32), sam(age:35)
In navy, tom(age:42), josh(age:35)
In air, jhona(age:34), samy(age:35)

最佳答案

只是循环:

var output = '';
for (var branch in responses) {
ouput += 'In ' + branch + ', ';
var people = responses[branch];
for (var i = 0; i < people.length; i++) {
output += people[i].name + '(age:' + people[i].age +')';
}
}

根据您添加的代码,您缺少一个分配:

var obj1= myArrays.responses; 
for (var key1 in obj1) {
console.log(key1);
var people = obj1[key1]; // get the people array
for (var i = 0; i < people.length; i++) {
console.log(people[i].name, people[i].age);
}
}

关于javascript - JSON 对象键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21685783/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com