1

Why does console.log(JSON.stringify(row.data)) returns undefined and how to fix it ?

From https://jsfiddle.net/ys6j038q/3/

  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(JSON.stringify(row.data));
    console.log(JSON.stringify(row.data));
  }
user310291
  • 36,946
  • 82
  • 271
  • 487

4 Answers4

3

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in#Array_iteration_and_for...in

You should not use for..in for arrays. In your row you have indexes, not values.

better solution:

rows.forEach(row => console.log(JSON.stringify(row.data)));
Maxx
  • 1,740
  • 10
  • 17
2

Because rows is an array.

Try this instead of the for loop.

rows.forEach(row => console.log(JSON.stringify(row.data)))

or

rows.forEach(function(row) { console.log(JSON.stringify(row.data)) })

forEach is an iterator that you can call on arrays

The forEach() method executes a provided function once per array element.

Docs on forEach

You could also use a for loop

for(var i = 0; i < rows.length; i++) {
    console.log(JSON.stringify(rows[i].data))
}
alex
  • 5,467
  • 4
  • 33
  • 43
1

Because row.data variable is undefined.

Working example:

for(var key in rows){
  console.log(JSON.stringify(rows[key].data))
}
1ven
  • 6,776
  • 1
  • 25
  • 39
1

Alternatively to using the foreach solutions, you could do this with a plain loop as well.

    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 i=0;i < rows.length;i++){
         console.log(JSON.stringify(rows[i].data));
      }
Dylan Meeus
  • 5,696
  • 2
  • 30
  • 49