gpt4 book ai didi

JavaScript 原生 groupBy 归约

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

我正在使用 JavaScript 原生 reduce,但是我想稍微改变分组以获得我想要的结果。我有一个数组如下:

const people = [
{name: "John", age: 23, city: "Seattle", state: "WA"},
{name: "Mark", age: 25, city: "Houston", state: "TX"},
{name: "Luke", age: 26, city: "Seattle", state: "WA"},
{name: "Paul", age: 28, city: "Portland", state: "OR"},
{name: "Matt", age: 21, city: "Oakland", state: "CA"},
{name: "Sam", age: 24, city: "Oakland", state: "CA"}
]

我想把它分组,改成这样:

const arranged = [
{
city: "Seattle",
state: "WA",
persons: [
{ name: "John", age: 23 },
{name: "Luke", age: 26}
]
},
{
city: "Houston",
state: "TX",
persons: [
{name: "Mark", age: 25}
]
},
{
city: "Portland",
state: "OR",
persons : [
{name: "Paul", age: 28}
]
},
{
city: "Oakland",
state: "CA",
persons: [
{name: "Matt", age: 21},
{name: "Sam", age: 24}
]
}
]

最佳答案

你可以使用 Map和一个字符串化对象作为分组的键。

稍后用键和分组的人的对象渲染想要的数组。

var people = [{ name: "John", age: 23, city: "Seattle", state: "WA" }, { name: "Mark", age: 25, city: "Houston", state: "TX" }, { name: "Luke", age: 26, city: "Seattle", state: "WA" }, { name: "Paul", age: 28, city: "Portland", state: "OR" }, { name: "Matt", age: 21, city: "Oakland", state: "CA" }, { name: "Sam", age: 24, city: "Oakland", state: "CA" }],
arranged = Array.from(
people.reduce((m, o) => {
var key = JSON.stringify(Object.assign(...['city', 'state'].map(k => ({ [k]: o[k] }))));
return m.set(key, (m.get(key) || []).concat({ name: o.name, age: o.age }));
}, new Map),
([key, persons]) => Object.assign(JSON.parse(key), { persons })
);

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

关于JavaScript 原生 groupBy 归约,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49436776/

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