gpt4 book ai didi

javascript - 需要一种有效的方法来对 javascript 中的对象数组进行分组

转载 作者:行者123 更新时间:2023-11-30 09:18:53 25 4
gpt4 key购买 nike

有没有办法通过引用数组中对象的特定值来对对象数组进行分组

假设我有一个名为

的数组
a=[
{name: "abc", address: "xxx"}
{name: "def", address: "yyy"}
{name: "xyz", address: "xyz"}
{name: "abc", address1: "123"}
{name: "def", address1: "456"}
]

我需要将同名地址添加到一个对象中,新数组应如下所示

b =[
{name:"abc", address: "xxx", address1: "123"}
{name:"def", address: "yyy", address1: "456"}
{name: "xyz", address: "xyz"}
]

最佳答案

您可以使用函数 reduce 按名称分组,并使用函数 Object.values 提取分组的对象。

let a = [{name: "abc", address: "xxx"},{name: "def", address: "yyy"},{name: "xyz", address: "xyz"},{name: "abc", address1: "123"},{name: "def", address1: "456"}],
result = Object.values(a.reduce((a, {name, ...rest}) => {
a[name] = Object.assign(a[name] || {name}, rest);
return a;
}, Object.create(null)));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 需要一种有效的方法来对 javascript 中的对象数组进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53121035/

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