-2

I have an objects with similar ids

[{
"_id": "603",
"name": 'innova',
"type": 'suv',
"brand": 'toyota'
},
{
"_id": "902",
"name": 'i20',
"type": 'hashback',
"brand": 'hyundai'
},
{
"_id": "603",
"name": 'indigo',
"type": 'haskback',
"brand": 'toyota'
}]

should be converted to

[{
"_id": "603",
"name": ['innova', 'indigo'],
"type": ['suv', 'haskback'],
"brand": ['toyota', 'toyota']
}, {
"_id": "902",
"name": ['i20'],
"type": ['hashback'],
"brand": ['hyundai']
}]

i have tried using Object.keys and Object.Values by pushing them if id already exits but failed.

1 Answers1

-1

Use the reduce function to build an object _id based. Then after use Object.values() to retrieve an object as you want

const data = [{
    "_id": "603",
    "name": 'innova',
    "type": 'suv',
    "brand": 'toyota'
  },
  {
    "_id": "902",
    "name": 'i20',
    "type": 'hashback',
    "brand": 'hyundai'
  },
  {
    "_id": "603",
    "name": 'indigo',
    "type": 'haskback',
    "brand": 'toyota'
  }
]

const newData = data.reduce((acc, row) => {

      if (!acc.hasOwnProperty(row._id)) {
      // there is no rows with the _id, we push a row into our accumulator
          acc[row._id] = {
            "_id": row._id,
            name: [row.name],
            type: [row.type],
            brand: [row.brand]
          };
        } else {
        // as the row with the _id exists, we just push values in the arrays
          acc[row._id].name.push(row.name);
          acc[row._id].type.push(row.type);
          acc[row._id].brand.push(row.brand);
        }

        return acc;
      }, {}); 
      
      console.log(Object.values(newData));
Maxime Girou
  • 1,511
  • 2
  • 16
  • 32