我正在做一些数据操作,但是我犯了一个错误并得到了错误的数据结构,所以最初我的数据是:(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}) )
], []);
答案 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