javascript - 对象数组 - 如何按属性对项目进行分组并将每个分组项目的数据压缩为 1

标签 javascript arrays array-map array-reduce

我正在尝试对主题中描述的数组执行操作。 我已经做了什么 - 按公共(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/

相关文章:

java - 读取数据的数组映射

javascript - 如果第二个对象数组具有相同的值,则将数组添加到对象数组内的对象

javascript - 占位符 IE9 - Javascript 未在 IE9 中执行

PHP 将值插入关联数组

ios - 使用 map 迭代时排除数组中的元素

javascript - 为什么 array_map 和 array_filter/array_reduce 的函数签名不同?

javascript - 单击外部组件时关闭弹出窗口

javascript - 从 JQuery DataTable 中删除行 - 但它会在重绘表后立即返回。我的 .JSP 数据源是原因吗?

javascript - parse.com 在数组中搜索部分字符串

php - JSON 到 MySQL 表