Search code examples
javascriptarraysobjectes6-modules

Combine values from an object within an object Javascript


I am trying to combine ids for an object. The original object looks like this:

{
   "Car1":{
      "139":{
         "count":3,
         "ids":[
            "336",
            "347",
            "453"
         ]
      },
      "140":{
         "count":1,
         "ids":[
            "338"
         ]
      }
   },
   "Car2":{
      "157":{
         "count":1,
         "ids":[
            "4449"
         ]
      }
   }
}

I am trying to combine the ids for each "car" so that it looks like this.

{
   "Car1":{
      "ids":[
         "336",
         "347",
         "453",
         "338"
      ]
   },
   "Car2":{
      "ids":[
         "4449"
      ]
   }
}

Basically just trying to create a function that reduces the unneeded information and combines the ids


Solution

  • You may use the Array.reduce

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

    Object.entries(data)
      .reduce((acc, [carName, carData]) => {
        acc[carName] = { ids: Object.values(carData).flatMap(({ids}) => ids) };
        return acc;
      },{});
    

    I further commented each line in the demo:

    const data = {
       "Car1":{
          "139":{"count":3,"ids":["336","347","453"]},
          "140":{"count":1, "ids":["338"]}
       },
       "Car2":{
          "157":{"count":1,"ids":["4449"]}
       }
    };
    
    const transformedData =
    //for all property name=>value pairs in data
    Object.entries(data)
      //return the reduced version...
      //for each couple as carName=>carData
      .reduce((acc, [carName, carData]) => {
        //sets the property carName in the accumulator
        acc[carName] = {
          //where the id property is the merge of all the ids found in the whole list
          ids: Object.values(carData).flatMap(({ids}) => ids)
        };
        return acc;
      },
      //inits the accumulator with empty object
      {});
    
    console.log(transformedData);