将对象数组的值映射到对象属性中

时间:2018-03-09 07:26:11

标签: javascript ecmascript-6

如何将对象值数组转换为对象属性?我想转这个

const array = [
  {
    "age_group": [
      {
        "range": "0-20",
        "total_count": 100
      },
      {
        "range": "21-30",
        "total_count": 200
      },
    ],
    "machine": {
      "name": "SK2DS0011",
    }
  }
]

进入这个

[{name: "SK2DS0011", "0-20": 100, "21-30": 200}]

我坚持使用reduce。

temp_arr = ori.reduce((accum, arr, i) => {
  return accum['abc'] = arr.age_data.map(o => ({[o.range]: o.count}))
},{})

也许我在reduce中使用了map错误。

2 个答案:

答案 0 :(得分:2)

您可以使用array#map生成对象数组。对于每个age_group,您可以使用array#map,扩展语法和Object.assign() 创建范围和total_count对象。您可以使用array_reduce生成所有范围的总和。



const array = [{ "age_group": [{ "range": "0-20", "total_count": 100 }, { "range": "21-30", "total_count": 200 }, ], "machine": { "name": "SK2DS0011", } }],
      result = array.map(({age_group, machine}) => {
        const {name} = machine;
        const obj = Object.assign(...age_group.map(({range, total_count}) => ({[range] : total_count})));
        const total = age_group.reduce((s,o) => s + +o.total_count, 0);
        return {name, ...obj, total};
      });
console.log(result);




答案 1 :(得分:0)

不使用reduce检查此解决方案。而是使用map来构造新数组:

const arr = [
  {
    "age_group": [
      {
        "range": "0-20",
        "total_count": 100
      },
      {
        "range": "21-30",
        "total_count": 200
      },
    ],
    "machine": {
      "name": "SK2DS0011",
    }
  }
];

// Use map to format the new array with the desired properties
let result = arr.map((x) => {
  // Get the 'name' property
  let obj = {
    name: x.machine.name,    
  };

  // Iterate over the 'age_group' array and add one property for each element
  var thisTotal = 0;
  for (var k in x.age_group) {
    let a = x.age_group[k];
    obj[a.range] = a.total_count;

    // Add this range to total
    thisTotal += a.total_count;
  }

  // Add the 'total' property
  obj.total = thisTotal;

  // Return the final array
  return obj;
});

console.log(result);