Home > Back-end >  How to combine the values which is array of the same property in the object's array javascript
How to combine the values which is array of the same property in the object's array javascript

Time:07-20

For the following array :

const a = [
  {
    26: [0],
    27: [100],
    28: [0]
  },
  {
    26: [0],
    27: [100],
    28: [0]
  },
  {
    26: [0],
    27: [100],
    28: [0]
  }
]

I need a function that should merge arrays with the same keys in the object.

`const result = [{
26: [0,0,0],
27: [100,100,100],
28: [0,0,0]
}]`

CodePudding user response:

You can simply achieve this by using Array.forEach() loop.

Live Demo :

const a = [{
  26: [0],
  27: [100],
  28: [0]
}, {
  26: [0],
  27: [100],
  28: [0]
}, {
  26: [0],
  27: [100],
  28: [0]
}];

let resObj = {};

a.forEach(obj => {
    Object.keys(obj).forEach(key => {
    resObj[key] ? resObj[key].push(...obj[key]) : resObj[key] = [...obj[key]]
  })
});

console.log([resObj]);

CodePudding user response:

Try to use reduce

const data = [{
    26: [0], 27: [100], 28: [0]
  },
  {
    26: [0], 27: [100], 28: [0]
  },
  {
    26: [0], 27: [100], 28: [0]
  }
];

const restructure = arr => 
  [arr.reduce((accumu, current) => {
    for (const [key, val] of Object.entries(current)) {
      accumu[key] = [...accumu[key] ?? '', ...val];
    }
    return accumu;
  }, {})];

console.log(restructure(data));

  • Related