gpt4 book ai didi

javascript - 我将如何在对象数组中连接和分组相似的值

转载 作者:行者123 更新时间:2023-12-04 08:18:26 25 4
gpt4 key购买 nike

我有一个对象数组

const array = [
{keyA: "HG 386893", count: 1, type: "dha"},
{keyA: "AL 386893", count: 1, type: "gop"},
{keyA: "HG 386893", count: 2, type: "ind"},
{keyA: "NC 386893", count: 1, type: "dha"},
{keyA: "HG 386893", count: 1, type: "gop"},
{keyA: "RO 386893", count: 1, type: "ind"}
];
我想合并基于类似的 key keyA属性(property)和连接 type并添加 count .所以最终结果将是:
const result = [
{keyA: "HG 386893", count: 4, type: "dha,ind,gop"},
{keyA: "AL 386893", count: 1, type: "gop"},
{keyA: "NC 386893", count: 1, type: "dha"},
{keyA: "RO 386893", count: 1, type: "ind"}
];
我实现的方式是:
  • 对数组进行排序 keyA
  • 循环遍历已排序的数组 & 如果前一个值 = 当前值,则添加 count并连接 type

  • 我知道这不是最佳解决方案,所以我需要一些帮助以更好的方式优化它。谢谢!

    最佳答案

    您可以使用 .reduce :

    const array = [
    { keyA: "HG 386893", count: 1, type: "dha" },
    { keyA: "AL 386893", count: 1, type: "gop" },
    { keyA: "HG 386893", count: 2, type: "ind" },
    { keyA: "NC 386893", count: 1, type: "dha" },
    { keyA: "HG 386893", count: 1, type: "gop" },
    { keyA: "RO 386893", count: 1, type: "ind" }
    ];

    const grouped = Object.values(array.reduce((acc,item) => {
    const { keyA, count, type } = item;
    const prev = acc[keyA];
    acc[keyA] = prev
    ? { ...item, count: prev.count+count, type: `${prev.type},${type}` }
    : item;
    return acc;
    }, {}));

    console.log(grouped);

    关于javascript - 我将如何在对象数组中连接和分组相似的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65602272/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com