在以下数据中。我想给它一个带有一些值作为键的对象,像这样:
从此处:链接到整个数据HERE(this.localObject)
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"},
{ "EmployeeID": "100A", "11-20": "40"},
{ "EmployeeID": "100A", "11-21": "50"},
{ "EmployeeID": "100A", "11-22": "60"},
{ "EmployeeID": "100B", "11-19": "1"},
{ "EmployeeID": "100B", "11-20": "2"},
{ "EmployeeID": "100B", "11-21": "3"},
{ "EmployeeID": "100B", "11-22": "4"}
]
//and so on...
到目前为止,我已经尝试过:
this.localData = this.localObject.employees;
const firstLevel = this.localData.map(x => x.aval);
firsLevel将为我提供一个与我需要的对象更接近的对象数组,现在我需要将“开始” 值作为键,并将“ ava” 在自己的对象容器中将value作为value属性
答案 0 :(得分:4)
您还需要迭代内部数组并构建一个数组。
var array = [{ 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" }] }],
result = array.reduce((r, { EmployeeID, aval }) => [
...r,
...aval.map(({ start, ava }) => ({ EmployeeID, [start]: ava }))
], []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:2)
您可以使用Array.flatMap
并像下面这样使用aval
遍历其中的Array.map
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"}
]
},
]
let res = employees.flatMap(({ EmployeeID, aval }) =>
aval.map(({ start, ava }) => ({ EmployeeID, [start]: ava })))
console.log(res)