Arnab Arnab - 1 year ago 74
Javascript Question

Flattening json such that one property is key and the other value

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:


Based on the answer here.. I tried..

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


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

Any help is sincerely appreciated.


Answer Source

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 = {
   item = item.sub.reduce(function(x,y) { return x[y.schema] =, x; }, item);
   delete item.sub;
   return item;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download