简体   繁体   中英

Convert an array of objects to a single object

I have an array as:

   [
      {
        path: 'default',
        moduleName: 'asset',
        masterName: 'assetType',
        data: [ { "code":"mov, "name":"Movable"} ]
      },
      {
        path: 'default',
        moduleName: 'common-master',
        masterName: 'city',
        data: [ { "code":"ind.ka.blr, "name":"Bangalore"},
                { "code":"ind.ka.mys, "name":"Mysore"}] ,
        {
        path: "default",
        moduleName: "common-master",
        masterName: "country",
        code:""
         }
       ]

I want to construct an object in javascript:

    Res: {
           Mdms: {
                    default: {
                              asset: { assetType: [ { "code":"mov, "name":"Movable"} ] },
                              common-master: { city: [ { "code":"ind.ka.blr, "name":"Bangalore"},
                                                       {"code":"ind.ka.mys, "name":"Mysore"}],
                                              country: [ {"code": "ind", "name": "India"},                                  
                                                        { "code": "usa", "name": "United States of America"},
                                                         { "code": "aus", "name": "Australia" },
                                                          {"code": "can", "name": "Canada"}]  
                                     }
                           }
                 }
         }

I tried reduce method but it is not generating the required output.

ResInfo = finalArray.reduce((ResInfo, arr) => {
  ResInfo[arr.path] = (ResInfo[arr.moduleName] || []).concat(arr);
})

Thanks in Advance!

You should use the reduce function for this, but you need to make a few changes. You can read more about reduce here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

// reduce takes as first argument an accumulator (your result) and the current element.
// what you will return will become the new accumulator
finalArray => finalArray.reduce((acc, el) => {
  const path = acc[el.path] || {};
  const moduleName = path[el.moduleName] || {};
  const masterName = moduleName[el.masterName] || [];
  return ({
    ...acc,
    // we merge the path of this object with the accumulator
    [el.path]: {
      ...path,
      // we merge the modulename of this object with the accumulator
      [el.moduleName]: {
        ...moduleName,
        // we merge the data array of this object with the accumulator
        [el.masterName]: [
          ...masterName,
          ...el.data
        ]
      }
    }
  });
}, {});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM