javascript – 转换嵌套数组 – >数组 – >对象转换数组 – >对象=>对象值:对象值

在下面的数据中.我想得到一个带有一些值作为键的对象,如下所示:

FROM HERE:链接到整个数据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会给我一个更接近我需要的对象数组,现在我需要将“start”值作为键,将“ava”值作为值属性放在自己的对象容器中

最佳答案
您还需要迭代内部数组并构建单个数组.

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; }

转载注明原文:javascript – 转换嵌套数组 – >数组 – >对象转换数组 – >对象=>对象值:对象值 - 代码日志