Arnab Arnab - 2 months ago 7
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:

[{"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

Answer

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