Nikit Patel Nikit Patel - 2 months ago 5
Javascript Question

formatting a json array of objects

I am trying to make a json array of objects.

My array is

var array=[{a:1,b:2,id:apple},{a:5,b:10,id:banana}]

I want to output it so that the array is of format:

[{source:apple, target:a ,value:1},{source:apple, target:b ,value:2},{source:banana, target:a ,value:5},{source:banana, target:b ,value:10}]

Help appreciated!!


You can use reduce() and Object.keys() to get this result.

var array=[{a:1,b:2,id:'apple'},{a:5,b:10,id:'banana'}];

var result = array.reduce(function(r, e) {
  Object.keys(e).forEach(function(k) {
    if(k != 'id') r.push({source:, target:k ,value:e[k]}) 
  return r;
}, []);