'Merge Multiple Arrays Of The Same ID Into One Object

if two objects in the data array contains same id the first will be picked and the other(s) discarded. multiple assets of same id should be in one object.

const myMap = cardDetails.map((card) => {
      return {
        id: card.id,
        amount: Number(card.amount),
        quantity: card.quantity,
        images: card.file,
      };
    });

    const data = {
      id: user?.userid,
      data: myMap,
    };

My goal with this data is to merge the arrays (myMap) that contains same id into one object. How can this be achieved?



Solution 1:[1]

it's not clear what you mean with multiple assets

I assume that you want some key to be merge together

You can achieve that easily using reduce and Object.values

like this

const myData = Object.values(cardDetails.reduce((res, {id,...card}) => {
  const existing = res[id] || {}
  return {
    ...res,
    [id]: {
      id,
      ...existing,
      ...card //here you need to change accordingly with your merge logic     
    }
  }
}, {}));

Solution 2:[2]

const groupData = (arr) => {
  const result = arr.reduce((acc, val) => {
    const existing = acc.find((obj) => obj.id == val.id)
    if (existing) {
     existing.data.push(val)
     }
     else {
      acc.push({ id: val.id, data: [val] })
     }
    
    return acc
  }, [])

  return result;
}

const arr = [
{id: 3, amount: 300, quantity: 77, images: ''}, 
{id: 3, amount: 400, quantity: 83, images: ''},
{id: 4, amount: 900, quantity: 48, images: ''}
]

console.log(groupData(arr))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 R4ncid
Solution 2 urchmaney