0

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?

Oge Obubu
  • 49
  • 10
  • if you are looking for a group by https://stackoverflow.com/questions/14446511/most-efficient-method-to-groupby-on-an-array-of-objects – cmgchess May 17 '22 at 05:49

2 Answers2

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     
    }
  }
}, {}));
R4ncid
  • 6,944
  • 1
  • 4
  • 18
  • This works fine pertaining to my question. Thank you! Now I intend to add the quantities for those objects with the same ID. – Oge Obubu May 17 '22 at 08:49
1

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))
urchmaney
  • 618
  • 5
  • 7