gpt4 book ai didi

javascript - 在对象数组中转换对象数组

转载 作者:行者123 更新时间:2023-12-01 15:53:56 25 4
gpt4 key购买 nike

我正在从足球 (soccer) API 中检索数据。我需要的具体数据是一个对象数组(306个对象)。每个对象都有一个名为 matchday 的属性,带有一个数值。我想将共享相同属性的所有对象分组并将它们存储在一个数组中。我最终需要的是一组对象数组。

对象数组示例:

[
{id: 264796, matchday: 1, …},
{id: 264797, matchday: 1, …},
{id: 264798, matchday: 2, …},
{id: 264800, matchday: 2, …},
]

我想要的是这样的:

[
[{id: 264796, matchday: 1, …},{id: 264797, matchday: 1, …}],
[{id: 264798, matchday: 2, …},{id: 264800, matchday: 2, …}],
]

最佳答案

您可以使用 .reduce()Object.values()获得所需的输出:

const data = [
{id: 264796, matchday: 1}, {id: 264797, matchday: 1},
{id: 264798, matchday: 2}, {id: 264800, matchday: 2}
];

const result = Object.values(
data.reduce((r, c) => {
r[c.matchday] = r[c.matchday] || [];
r[c.matchday].push(c);
return r;
}, {})
);

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

关于javascript - 在对象数组中转换对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60740219/

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