0

I have data in following format..

var array = [{"name":"abc","boss":"def","sub":[{"schema":"a","data":1},{"schema":"b","data":0},{"schema":"c","data":0}]},
.
.
.
]

I wish to transform it to the following structure:

[{"name":"abc","boss":"def","a":1,"b":0,"c":0},
    .
    .
    .
    ]

Based on the answer here.. I tried..

grouped = [];
array.forEach(function (a) {
    if (!this[a.name]||!this[a.boss]) {
        this[a.name] = { name: a.name, boss:a.boss };
        grouped.push(this[a.name]);
       }
    this[a.name][a.sub.schema] = (this[a.name][a.sub.schema] || 0) + a.sub.data;
}, Object.create(null));

console.log(grouped);

The above gives undefined:NaN as the third property in the result objects..

Any help is sincerely appreciated.

Thanks

Community
  • 1
  • 1
Arnab
  • 2,324
  • 6
  • 36
  • 60

2 Answers2

2

You probably want to reduce the sub object to properties of the item.

The following code maps the items in array to a new array, which contains the flattened items:

array = array.map(function(item) {
   item = item.sub.reduce(function(x,y) { return x[y.schema] = y.data, x; }, item);
   delete item.sub;
   return item;
});
David Hedlund
  • 128,221
  • 31
  • 203
  • 222
2

Try this simply.

var arr = [];
array.forEach(function(ele){
  var obj = {};obj.name=ele.name;
  obj.boss=ele.boss;
  ele.sub.forEach(function(e){
    obj[e.schema] = e.data
  });
  arr.push(obj)
});
AB Udhay
  • 643
  • 4
  • 9