简体   繁体   中英

Reduce Array of objects to object of objects

I want to convert an Array of objects to Object of Objects.

My data:

var pools = [{
    dce: 3,
    lts: 2,
    name: "nift nation",
  },
  {
    dce: 1049.99,
    lts: 104.999,
    name: "NSG I.NS. Mark Select",
  },
  {
    dce: 162,
    lts: 36.157,
    name: "Shift-Team Mark Select",
  }
]

Desired output:

{
  nift_nation: {
    nift_nationDollars: "",
    nift_nationUnits: "",
    nift_nationPercentage: ""
  },
  NSG_I$NS$_Mark_Select: {
    NSG_I$NS$_Mark_SelectDollars: "",
    NSG_I$NS$_Mark_SelectUnits: "",
    NSG_I$NS$_Mark_SelectPercentage: ""
  },
  Shift__Team_Mark_Select: {
    Shift__Team_Mark_SelectDollars: "",
    Shift__Team_Mark_SelectUnits: "",
    Shift__Team_Mark_SelectPercentage: ""
  }
}

 var pools = [{ dce: 3, lts: 2, name: "nift nation", }, { dce: 1049.99, lts: 104.999, name: "NSG I.NS. Mark Select", }, { dce: 162, lts: 36.157, name: "Shift-Team Mark Select", } ] var suffixArray = ["Dollars", "Percentage", "Units"]; var getFieldSuffix = function(rowFieldCount) { switch (rowFieldCount) { case 0: return 'Dollars'; case 1: return 'Units'; case 2: return 'Percentage'; default: return } }; var replacementMap = { single_space: '_', dot: '$', hyphen: '__', }; var replacer = function(str) { return str.replace(/[ .-]/g, l => { if (l == ".") return replacementMap["dot"]; if (l == " ") return replacementMap["single_space"]; return replacementMap["hyphen"]; }); }; var formStructure = function dataFormatter(collection, suffixArr) { const data = collection.map(pool => Object.assign({ [replacer(pool.name)]: suffixArr.reduce((acc, suffix, index) => { acc[replacer(pool.name) + getFieldSuffix(index % 3)] = ''; return acc; }, {}), })); return Object.assign({}, ...data); //Extra step, I don't think this is the best way } var arrObj = formStructure(pools, suffixArray); console.log(arrObj) 

I get the desired output. In formStructure function I store the result that is an Array of Objects in variable data , then in the next step return Object.assign({}, ...data); , I convert it into Object of objects . This approach is not optimum.

I want to be able to get Object of objects in variable data itself.

You can use exactly the same reduce approach that you are already using on the suffixArr for your collection :

function formStructure(collection, suffixArr) {
  return collection.reduce(acc, pool) => {
    acc[replacer(pool.name)] = suffixArr.reduce((acc, suffix, index) => {
      acc[replacer(pool.name) + getFieldSuffix(index % 3)] = '';
      return acc;
    }, {});
    return acc;
  }, {});
}

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