1

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] } },
];

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Anna
  • 914
  • 9
  • 25
  • Why is your ideal an array of heterogeneous objects? That's going to be more difficult to work with. – jonrsharpe May 23 '22 at 08:39
  • var output={}; inputBl.forEach(i=>{ if(!output[i.model]) { output[i.model]={dimentions:[i.dim], values:[i.val]} }else{ output[i.model]={dimentions:[...output[i.model].dimentions , i.dim], values:[...output[i.model].values ,i.val]} } }); – Tran Loc May 23 '22 at 11:07

0 Answers0