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

4 Answers 4

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)));
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

1

Because row.data variable is undefined.

Working example:

for(var key in rows){
  console.log(JSON.stringify(rows[key].data))
}

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.