簡體   English   中英

將對象數組簡化為對象對象

[英]Reduce Array of objects to object of objects

我想將對象數組轉換為對象對象。

我的資料:

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",
  }
]

所需的輸出:

{
  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) 

我得到所需的輸出。 formStructure函數中,我將對象數組存儲在變量data ,然后在下一步中return Object.assign({}, ...data); ,我將其轉換為對象的Object 這種方法不是最佳的。

我希望能夠獲取變量data本身中的對象的Object

您可以使用與在suffixArr collection上已經使用的完全相同的reduce方法:

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;
  }, {});
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM