如何从嵌套对象中获取x,y

时间:2016-08-08 16:48:36

标签: javascript json node.js

我在line console.log(row.data.x)上有错误,请参阅https://jsfiddle.net/ys6j038q/

- name: Sync /etc/spark/conf to $SPARK_HOME/conf
  synchronize: src=/etc/spark/conf dest={{spark_home}} copy_links=true
  delegate_to: "{{ inventory_hostname }}"
  tags: spark

3 个答案:

答案 0 :(得分:4)

您可以在此上下文中使用forEach而不是for..in

rows.forEach(function(row){
  console.log(row.data.x);
  console.log(row.data.y);
});

for..in将为您提供该数组对象的可枚举属性,例如01。它不会给出数组中的元素。

DEMO

答案 1 :(得分:1)

而不是rows[row]



 var data = '{"data":{"time":"2016-08-08T15:13:19.605234Z","x":20,"y":30}}{"data":{"time":"2016-08-08T15:13:19.609522Z","x":30,"y":40}}';

 var sanitized = '[' + data.replace(/}{/g, '},{') + ']';
 var rows = JSON.parse(sanitized);
 //console.log(rows);

 for (var row in rows) {
   console.log(rows[row].data.x);
   console.log(rows[row].data.y);
 }




答案 2 :(得分:1)

  

用 -

替换你的for循环
for(var i=0;i<rows.length;i++){

  console.log(rows[i].data.x);
  console.log(rows[i].data.y);
}