gpt4 book ai didi

javascript - 对象数组,按对象键 :value 分组

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

我有一个这样的对象数组:

const data = [
{ id: 1, type: { name: "A" }, condition: "new" },
{ id: 2, type: { name: "C" }, condition: "broken" },
{ id: 3, type: { name: "C" }, condition: "brand new" },
{ id: 4, type: { name: "B" }, condition: "broken" },
{ id: 5, type: { name: "C" }, condition: "brand new" },
{ id: 6, type: { name: "A" }, condition: "new" },
{ id: 7, type: { name: "A" }, condition: "new" },
{ id: 8, type: { name: "B" }, condition: "broken" },
{ id: 9, type: { name: "C" }, condition: "broken" }
];

我想做的是按类型的 key:value 对这些对象进行分组,在本例中为 name:value,如下所示:

const data = [
{
by: {
type: { name: "A" }
},
chunks: [
{ id: 1, type: { name: "A" }, condition: "new" },
{ id: 6, type: { name: "A" }, condition: "new" },
{ id: 7, type: { name: "A" }, condition: "new" }
]
},
{
by: {
type: { name: "C" }
},
chunks: [
{ id: 2, type: { name: "C" }, condition: "broken" },
{ id: 3, type: { name: "C" }, condition: "brand new" },
{ id: 5, type: { name: "C" }, condition: "brand new" },
{ id: 9, type: { name: "C" }, condition: "broken" }
]
},
{
by: {
type: { name: "B" }
},
chunks: [
{ id: 4, type: { name: "B" }, condition: "broken" },
{ id: 8, type: { name: "B" }, condition: "broken" }
]
},
];

我尝试使用 lodash 和 Array.prototype.reduce() ,我最后一次尝试使用 lodash,但我无法将类型作为对象。

_.chain(channels)
.groupBy("type.name")
.map((item, i) => {
return {
chunks: item,
by: i
};
})
.value();

最佳答案

您可以使用 Map 按组收集数据,然后其 values() 方法将根据需要迭代数据:

const data = [{ id: 1, type: { name: "A" }, condition: "new" },{ id: 2, type: { name: "C" }, condition: "broken" },{ id: 3, type: { name: "C" }, condition: "brand new" },{ id: 4, type: { name: "B" }, condition: "broken" },{ id: 5, type: { name: "C" }, condition: "brand new" },{ id: 6, type: { name: "A" }, condition: "new" },{ id: 7, type: { name: "A" }, condition: "new" },{ id: 8, type: { name: "B" }, condition: "broken" },{ id: 9, type: { name: "C" }, condition: "broken" }];

const map = new Map(data.map(o => [o.type.name, { by: { type: o.type.name }, chunks: [] }]));
data.forEach(o => map.get(o.type.name).chunks.push(o));
const result = [...map.values()];

console.log(result);

关于javascript - 对象数组,按对象键 :value 分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54834179/

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