我试图显示对象数组中所有键-值对的值。我尝试了几种方法,例如http://jsfiddle.net/4Mrkp/,但是我似乎不能让它在我的数据上工作。
数据,我只想显示汽车制造:
{
"response":{
"status":"200",
"messages":{},
"milliseconds":"2"
},
"input":{
"provinceid":{},
"supplierid":"12345678",
"statusid":{ }
},
"output":{
"count":"7",
"list":{
"make":[
{"name":"Alfa Romeo"},
{"name":"Audi"},
{"name":"BMW"},
{"name":"Chevrolet"},
{"name":"Chrysler"},
{"name":"Citroen"},
{"name":"Dacia"}
]
}}
}到目前为止,我的代码显示了单词make
function display_makes(obj)
{
document.getElementById("temp-id").innerHTML =
Object.keys(obj.output.list.make).forEach(function(key){
document.write(key);});
}因此,下一步是获取make的每个元素的值,但是如何获取呢?有什么想法吗?
发布于 2016-09-24 17:57:01
不要在obj.output.list.make上使用Object.keys,因为它是一个数组,请使用:
obj.output.list.make.forEach(function(obj) {
console.log(obj.name);
});发布于 2016-09-24 17:49:01
您可以使用underscoreJS来操作JSON。
var make = _.map(json_object.output.list.make,function(make) {
document.write(make.name);
return make;
}) 这个make变量将包含键值对中的值。
发布于 2016-09-24 17:56:36
这比你想象的要容易。只需迭代数组并忘记其余部分:
object.output.list.make.forEach(function(item){
document.write(item);
});您使用的是阵列,因此根本不需要Object.keys()
https://stackoverflow.com/questions/39674890
复制相似问题