user310291 user310291 - 4 months ago 13
Javascript Question

How to get x, y from nested object

I have an error on line console.log(row.data.x) see https://jsfiddle.net/ys6j038q/

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(row.data.x);
console.log(row.data.y);
}

Answer

You could use forEach at this context not for..in

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

for..in will give you the enumerable properties from that array object such as 0 and 1. It will not give the elements in the array.

DEMO