我正在尝试对主题中描述的数组执行操作。我已经完成的工作 - 按公共属性 + 将每个项目的映射数据分组到所需的格式。它是通过在其中使用reduce + map函数实现的。现在我需要将每个分组项目属性压缩为 1 的最后一部分。我的目标是使其正常工作,最好是通过扩展重组功能。
要重组的数组
const arrToRestructure = [
{
x: "test-x1",
y: "test-y1",
data: [
{id: 1, label: "label-y1-1"},
{id: 2, label: "label-y1-2"}
]
},
{
x: "test-x2",
y: "test-y1",
data: [
{id: 1, label: "label-y1-3"},
{id: 2, label: "label-y1-4"}
]
},
{
x: "test-x2",
y: "test-y2",
data: [
{id: 1, label: "label-y2-1"},
{id: 2, label: "label-y2-2"}
]
},
]
重组功能
const restructureArr = () => {
const restructuredArr = arrToRestructure.reduce(
(prevVal, nextVal) => ({
...prevVal,
[nextVal["y"]]: [
...(prevVal[nextVal["y"]] || []),
nextVal.data.map((nextVal) => nextVal.label),
]})
,[]);
return restructuredArr;
}
电流输出
{
"test-y1": [
[
"label-y1-1",
"label-y1-2"
],
[
"label-y1-3",
"label-y1-4"
]
],
"test-y2": [
[
"label-y2-1",
"label-y2-2"
]
]
}
期望的输出
{
"test-y1": [
"label-y1-1",
"label-y1-2",
"label-y1-3",
"label-y1-4",
],
"test-y2": [
"label-y2-1",
"label-y2-2"
]
}