Search code examples
javascriptlodash

How to create array of multiple objects from object that represents objects


I want to converts: {port:{0: 23, 1: 22},protocol:{0: "http",1:' "https"}}

to: [{port: 23, protocol: 'http' },{port: 22, protocol: 'https' }]

I already wrote function to do it manually.

Is there any lodash function that does that? or manipulate an existing function to get the desired result?


Solution

  • There isn't a single lodash function that does that, but you can create a function via _.flow() to get the desired result.

    You can convert the object to an array of arrays that contain the label and values, _.unzip() to transpose, and then map to objects using _.zipObject():

    const obj = { port: {0: 23, 1: 22}, protocol: {0: "http",1: "https"} };
    
    const fn = _.flow([
      o => _.map(o, (v, k) => [k, ..._.values(v)]), // convert to an array of label, ...values
      _.unzip, // transpose
      ([labels, ...values]) => _.map(values, v => _.zipObject(labels, v)) // create the ojects
    ]);
    
    const result = fn(obj);
    
    console.log(result);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>