将对象数组减少为对象对象

时间:2019-02-14 13:58:51

标签: javascript

我想将对象数组转换为对象对象。

我的数据:

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);中,将其转换为对象的对象。这种方法不是最佳方法。

我希望能够在变量data本身中获取对象

1 个答案:

答案 0 :(得分:2)

您可以为reduce使用与suffixArr上已经使用的完全相同的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;
  }, {});
}