Oge Obubu
Oge Obubu

Reputation: 69

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?

Upvotes: 0

Views: 602

Answers (2)

urchmaney
urchmaney

Reputation: 618

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))

Upvotes: 1

R4ncid
R4ncid

Reputation: 7139

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     
    }
  }
}, {}));

Upvotes: 1

Related Questions