gpt4 book ai didi

javascript - 使用groupBy时向JS中的对象添加值

转载 作者:行者123 更新时间:2023-11-28 14:18:02 24 4
gpt4 key购买 nike

当两个项目具有相同的 typeId 时,我使用 mapValuesgroupBy 进行分组并创建 key

例如原始数据是

{
"Name": "One",
"typeId": 1
},
{
"Name": "Two",
"typeId": 2
},
{
"Name": "One Two",
"typeId": 1
},
{
"Name": "Three",
"typeId": 3
},
{
"Name": "Three Two",
"typeId": 3
}

并通过使用groupBy,我将具有匹配typeId的对象分组,并省略来自`对象作为...

const GroupedTypes = Object.entries(
_.mapValues(_.groupBy(data, 'typeID'), rlist =>
rlist.map(type => _.omit(type, 'typeID'))
)
);

按计划返回...

[
"1",
[
{
"Name": "One",
},
{
"Name": "One Two",
}
]
],
[
"2",
[
{
"Name": "Two",
}
]
],
[
"3",
[
{
"Name": "Three",
}
],
[
{
"Name": "Three Two",
}
]
]

但是,我还想从第一个 0 对象中的值 Name 添加一个 Name 对象。因此最终会得到类似的结果..

[
"1",
"One",
[
{
"Name": "One",
},
{
"Name": "One Two",
}
]
],
[
"2",
"Two",
[
{
"Name": "Two",
}
]
],
[
"3",
"Three",
[
{
"Name": "Three",
}
],
[
{
"Name": "Three Two",
}
]
]

我一直在浏览 lodash 文档,但找不到有效的方法。我怎样才能实现这个目标?

最佳答案

您可以使用reduce根据 typeId 对项目进行分组:

const input=[{"Name":"One","typeId":1},{"Name":"Two","typeId":2},{"Name":"One Two","typeId":1},{"Name":"Three","typeId":3},{"Name":"Three Two","typeId":3}]

const merged = input.reduce((acc, { Name, typeId }) => {
acc[typeId] = acc[typeId] || [ typeId, Name, []];
acc[typeId][2].push({ Name });
return acc;
}, {})

console.log(Object.values(merged))

您需要创建一个累加器对象,其中每个 typeId 作为键,并将输出中所需的数组作为其值。如果该键尚不存在,请使用 [ typeId, Name, []] 作为值添加该键。这样,第一个项目的 Name 将出现在输出中。这是累加器/合并的样子:

{
"1": [1, "One", [{ "Name": "One" }, { "Name": "One Two" }]],
"2": [2, "Two", [{ "Name": "Two" }]],
"3": [3, "Three", [{ "Name": "Three" }, { "Name": "Three Two" }]]
}

然后使用,Object.values()仅获取此对象的值作为数组

关于javascript - 使用groupBy时向JS中的对象添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56616230/

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