gpt4 book ai didi

javascript - 从稍微嵌套的数组中删除重复项后保留对象的所有键

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

我有同样的 this question 问题,但我的对象有更多的键,例如:

[{
id: 1
name: "abcd",
value: 123,
type: "foo"
},
{
id: 1
name: "abcd",
value: 321,
type: "faa"
},
{
id: 2
name: "dcba",
value: 456,
type: "baa"
}]

我想实现这样的目标:

[{
id: 1,
name: "abcd",
value: [123, 321],
type: ["foo", "faa"]
},
{
id: 2
name: "dcba",
value: [456],
type: ["baa"]
}]

额外的键具有相同的值。

最佳答案

想法是按id分组,然后映射每组对象,从第一个对象中选择idname,从组中的所有对象中提取所有 valuetype,转置并压缩到另一个对象,然后合并它们。

const { pipe, groupBy, prop, values, map, converge, merge, head, pick, props, transpose, zipObj } = R

const fn = pipe(
groupBy(prop('id')), // groupBy the id
values, // convert the object of groups to array of groups
map(converge(merge, [ // map each group by merging the results of...
pipe(head, pick(['id', 'name'])), // getting the id and name from the 1st item
pipe(map(props(['value', 'type'])), transpose, zipObj(['value', 'type'])) // extract the value and type and zipping to an object
]))
)

const data = [{
id: 1,
name: "abcd",
value: 123,
type: "foo"
},
{
id: 1,
name: "abcd",
value: 321,
type: "faa"
},
{
id: 2,
name: "dcba",
value: 456,
type: "baa"
}]

const result = fn(data)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>

关于javascript - 从稍微嵌套的数组中删除重复项后保留对象的所有键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58313217/

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