I am struggling with merging an array of objects on the same key - "model" and restructuring it.
It should be also dynamic.
Original Array
var inputBl = [
{ model: 1, dim: 'd1', val: 'v1' },
{ model: 2, dim: 'd2', val: 'v2' },
{ model: 1, dim: 'd3', val: 'v3' },
]
First I got all unique model keys:
var keys = [];
inputBl.forEach(function(item) {
keys.push(item.model);
});
let uniqueItems = [...new Set(keys)];
And then tried to restructure the object:
var obj = [];
uniqueItems.forEach(function(model) {
inputBl.forEach(function(item) {
if (item.model == model) {
obj.push({model: {dimensions: [item.dim]}})
}
});
});
But I get:
[ { model: [d1] }, { model: [d2] }, { model: [d3] }]
The ideal result (dynamic):
var ideal = [
{ 1: { dimensions: [d1, d3], values: [v1, v3] } },
{ 2: { dimensions: [d2], values: [v2] } },
];