我正在尝试对主题中描述的数组执行操作。 我已经做了什么 - 按公共(public)属性分组+将每个项目的数据映射到所需的格式。是通过里面使用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"
]
}
最佳答案
每次只需传播 Array#map
结果:
const restructureArr = () => {
const restructuredArr = arrToRestructure.reduce((prevVal, nextVal) => ({
...prevVal,
[nextVal["y"]]: [
...(prevVal[nextVal["y"]] || []),
...nextVal.data.map((nextVal) => nextVal.label), // fix
]
}) , []);
return restructuredArr;
}
一些增强功能:
const restructureArr = (arrToRestructure = []) =>
arrToRestructure.reduce((acc, { y, data = [] }) => ({
...acc,
[y]: [
...(acc[y] || []),
...data.map(({ label }) => label),
]
}), []);
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"} ] }
];
console.log(restructureArr(arrToRestructure));
关于javascript - 对象数组 - 如何按属性对项目进行分组并将每个分组项目的数据压缩为 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70915623/