Search code examples
javascriptarraysobjectlodash

Transform array of objects to another array of objects


i am currently struggling to transform an array of objects to fit my needs.

My initial array is looking like this:

 [{
    "adId": "uuid"
    "carBrand": "audi",
    "carColor: "blue",
    "carType": "sedan"
    "yearOfProduction": 1999,
    "price": 10.000
  },{
    "adId": "uuid"
    "carBrand": "mercedes",
    "carColor: "yellow",
    "carType": "coupe"
    "yearOfProduction": 2004,
    "price": 14.000
  },{
    "adId": "uuid"
    "carBrand": "bmw",
    "carColor: "green",
    "carType": "minivan"
    "yearOfProduction": 2007,
    "price": 6.000
 }]

I would like that my new array look like this:

[{
    "adId": "uuid"
    "carBrand": "audi",
    "carColor: "blue"
},{
    "adId": "uuid"
    "carBrand": "audi",
    "carType: "sedan"
},{
    "adId": "uuid"
    "carBrand": "audi",
    "yearOfProduction: "1999"
},{
    "adId": "uuid"
    "carBrand": "audi",
    "price: 10.000
},
{
    "adId": "uuid"
    "carBrand": "mercedes",
    "carColor: "yellow"
},{
    "adId": "uuid"
    "carBrand": "mercedes",
    "carType: "coupe"
},{
    "adId": "uuid"
    "carBrand": "mercedes",
    "yearOfProduction: "2004"
},{
    "adId": "uuid"
    "carBrand": "mercedes",
    "price: 14.000
},
    {
    "adId": "uuid"
    "carBrand": "bmw",
    "carColor: "green"
},{
    "adId": "uuid"
    "carBrand": "bmw",
    "carType": "minivan"
},{
    "adId": "uuid"
    "carBrand": "bmw",
    "yearOfProduction": 2007,
},{
    "adId": "uuid"
    "carBrand": "bmw",
    "price": 6.000
}]

So basically "adId" and "carBrand" properties would be present on every new object together with each one of the properties that is left. I've tried various scenarios with lodash but i simply can't make it. Any suggestions and hints are welcome, cheers.


Solution

  • You can easily achieve the result using flatMap and Object.entries

    One-liner

    arr.flatMap(({ adId, carBrand, ...rest }) => Object.entries(rest).map(([k, v]) => ({ adId, carBrand, [k]: v })))
    

    const arr = [
      {
        adId: "uuid",
        carBrand: "audi",
        carColor: "blue",
        carType: "sedan",
        yearOfProduction: 1999,
        price: 10.0,
      },
      {
        adId: "uuid",
        carBrand: "mercedes",
        carColor: "yellow",
        carType: "coupe",
        yearOfProduction: 2004,
        price: 14.0,
      },
      {
        adId: "uuid",
        carBrand: "bmw",
        carColor: "green",
        carType: "minivan",
        yearOfProduction: 2007,
        price: 6.0,
      },
    ];
    
    const result = arr.flatMap(({ adId, carBrand, ...rest }) => {
      return Object.entries(rest).map(([k, v]) => ({ adId, carBrand, [k]: v }));
    });
    
    console.log(result);