How do I merge data with the same ID?

sample data:


const data = [
  {
    name: "Anne",
    quantity: 8,
    color: "Green",
    id: "1823817334"
  },
  {
    id: "1823817334",
    color: "Black",
    quantity: 1,
    name: "Anne"
  }
];

As you’ve noticed here, they have the same IDs. How do I combine if the data has the same IDs to something like this?

const data = [
  {
    name: "Anne",
    id:  "1823817334",
    selections: [
      { color: "Green", quantity: 8 },
      { color: "Pink", quantity: 1 }
    ]
  }
];

I have recreated this in te codesandbox as well:

So far, This is how I displayed the data:

 <div className="App">
      {Object.entries(data).map(([key, value]) => {
        return (
          <p key={key}>
            <li>{value.name + value.color + value.quantity}</li>
          </p>
        );
      })}
      ;
    </div>

Well, how you display it is a different question. The question you are asking is about data manipulation. You need to transform one data object into another.

But it still isn’t clear to me. Will there always be only one id in the array? Or do you need to account for multiple?

You could do this with a for loop, but a reduce would work, too. You have to go through the elements and check if the new element for that is created - if not, create it; if it is, and your data. If you’re using a for loop, then create a new array and push onto it. If you’re using reduce, then you’re just reducing down to an array.

You need a helper function and work from there


function helperFx(data){
  let obj = {} 
  for(let [key, val] of Object.entries(data)){
    
    const {name, id, color, quantity} = val
    // check if obj has a key of selections if not  
    if( !('selections' in obj) ) obj['selections'] = []
    // if id matches then lets add the name and another id and push them values
    if(id === '1823817334'){
      obj.name = name
      obj.id = 'hdrezmDjPXcBVfYkusie'
      obj['selections'].push({ color, quantity })
    }
  }
  return obj
}

Yes, there will always be one id in the array

I tried this and it worked, thank you

Hello, how would I display it in the screen? I tried with these but failed.

{value} will show this error :

Objects are not valid as a React child (found: object with keys {color, quantity}). If you meant to render a collection of children, use an array instead.

{value.id} or the {value.name} will show as undefined

 {Object.entries(value).map(([key, value]) => {
        return (
          <p key={key}>
            <li>
              {key}
              {value}
              {console.log(value.id)} //this will show as undefined
            </li>
          </p>
        );
      })}