2016-09-24 36 views
1

我试图显示对象数组中所有键值对的值。我已经尝试了几种方法,例如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,但是如何?有什么想法吗?

+0

对于'obj.output.list.make'中的每个'value',你都需要'value.name'。 – Biffen

回答

0

不要因为它是一个数组,使用上obj.output.list.make使用Object.keys

obj.output.list.make.forEach(function(obj) { 
    console.log(obj.name); 
}); 
+0

谢谢,这解决了它! – ILE

0

您可以使用underscoreJS来操纵JSON。

var make = _.map(json_object.output.list.make,function(make) { 
    document.write(make.name); 
    return make; 
}) 

这个make变量将包含键值对中的值。

0

它比你想象的要容易。只是遍历数组了,忘了休息:

object.output.list.make.forEach(function(item){ 
    document.write(item); 
}); 

您与阵列工作,因此你并不需要在所有的Object.keys()

+0

感谢您的回复!这改变了document.write(item); into document.write(item.name); – ILE