Search code examples
javascriptjsonecmascript-6ecmascript-5

How to retrieve JSON data from array of JSON?


Writing a JS code to loop over an array and get the values. Getting value as object on iterating through array.

Here is the actual JSON that's to be looped over.

[ { sum: '[object Object]', count: '[object Object]' },
  { sum: '[object Object]', count: '[object Object]' },
  { sum: '[object Object]', count: '[object Object]' },
  { sum: '[object Object]', count: '[object Object]' },
  { sum: '[object Object]', count: '[object Object]' },
  { sum: '[object Object]', count: '[object Object]' },
  { sum: '[object Object]', count: '[object Object]' } ]

Sample code to iterate over array:

var data = [ { sum: '[object Object]', count: '[object Object]' },
  { sum: '[object Object]', count: '[object Object]' },
  { sum: '[object Object]', count: '[object Object]' },
  { sum: '[object Object]', count: '[object Object]' },
  { sum: '[object Object]', count: '[object Object]' },
  { sum: '[object Object]', count: '[object Object]' },
  { sum: '[object Object]', count: '[object Object]' } ]



function newX(data) {
    console.log(data.length);
    for (var i = 0; i < data.length; i++) {
        console.log(JSON.stringify(data[i]));
    }
}
newX(data);

Output:

{"sum":"[object Object]","count":"[object Object]"}
{"sum":"[object Object]","count":"[object Object]"}
{"sum":"[object Object]","count":"[object Object]"}
{"sum":"[object Object]","count":"[object Object]"}
{"sum":"[object Object]","count":"[object Object]"}
{"sum":"[object Object]","count":"[object Object]"}
{"sum":"[object Object]","count":"[object Object]"}

but here need to see the actual values.

please let me know on how can I do it.

Thanks


Solution

  • Edit: The mistake really just is calling .log() on an jsObject and not it's properties. console.log(data[i].sum) is the only thing you have to change :D

    The function toString on an object outputs [object Object] (if it's a plain object), so you probably tried to output an object without any of it's properties, fix that and your console.log will work :)

    var data = [ { sum: 'xx', count: 'yy' },
      { sum: 'xy', count: 'yx' }]
    
    
    
    function newX(data) {
        console.log(data.length);
        for (var i = 0; i < data.length; i++) {
            console.log("sum: " + data[i].sum + "\ncount: " + data[i].count); 
        }
    }
    newX(data);