Reduce()一个已经被减少的元素的对象

时间:2018-11-24 22:50:38

标签: javascript arrays angular object reduce

我正在做一些数据操作,但是我犯了一个错误并得到了错误的数据结构,所以最初我的数据是:(link to data)

const employees = [{
    "EmployeeID": "100A",
    "FirstName": "Downs",
    "aval": [
       {"start": "11-19", "end": "2", "ava": "30", "health": "4"},
       {"start": "11-20", "end": "2", "ava": "40", "health": "4"},
       {"start": "11-21", "end": "2", "ava": "50", "health": "4"},
       {"start": "11-22", "end": "2", "ava": "60", "health": "4"}
    ]
  },
  {
    "EmployeeID": "100B",
    "FirstName": "Mckenzie",
    "aval": [
       {"start": "11-19", "end": "2", "ava": "1", "health": "4"},
       {"start": "11-20", "end": "2", "ava": "2", "health": "4"},
       {"start": "11-21", "end": "2", "ava": "3", "health": "4"},
       {"start": "11-22", "end": "2", "ava": "4", "health": "4"}
    ]
  },

]

,并希望得到它:

const employees = [
   { "EmployeeID": "100A", "11-19": "30", "11-20": "40", "11-21": "50", "11-22": "60"},
   { "EmployeeID": "100B", "11-19": "1", "11-20": "2", "11-21": "3", "11-22": "4"}
]

我问了一下,这给了我10个对象而不是2个对象,只需要将那些讨厌的employeeID放在所有初始值都包含在1个对象中即可。

const res = employees.reduce((acc, { EmployeeID, aval}) => [
      ...acc,
      ...aval.map( ({ start, ava}) => ({ EmployeeID, [start]: ava}) )
    ], []);

1 个答案:

答案 0 :(得分:3)

由于输入项和输出项是一对一的,因此应在drawable上使用.map而不是employees

.reduce

或者,如果您想创建更少的废弃中间对象,则可以const employees=[{"EmployeeID":"100A","FirstName":"Downs","aval":[{"start":"11-19","end":"2","ava":"30","health":"4"},{"start":"11-20","end":"2","ava":"40","health":"4"},{"start":"11-21","end":"2","ava":"50","health":"4"},{"start":"11-22","end":"2","ava":"60","health":"4"}]},{"EmployeeID":"100B","FirstName":"Mckenzie","aval":[{"start":"11-19","end":"2","ava":"1","health":"4"},{"start":"11-20","end":"2","ava":"2","health":"4"},{"start":"11-21","end":"2","ava":"3","health":"4"},{"start":"11-22","end":"2","ava":"4","health":"4"}]},]; const res = employees.map(({ EmployeeID, aval }) => ( Object.assign( { EmployeeID }, ...aval.map(({ start, ava }) => ({ [start]: ava })) ) )); console.log(res);内部数组reduce而不是aval

.map