How to Get X, Y from Nested Object [Duplicate]

I have an error on line console.log(row.data.x) see

  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);
  }
2

3 Answers

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

3

It would be rows[row] instead

 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);
 }

Replace your for loop with-

for(var i=0;i<rows.length;i++){

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

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest