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?

1

2 Answers 2

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     
    }
  }
}, {}));
Sign up to request clarification or add additional context in comments.

1 Comment

This works fine pertaining to my question. Thank you! Now I intend to add the quantities for those objects with the same ID.
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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.