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

Keep all the keys of the object after removing duplicates from a slightly nested array

我遇到了 的相同问题,但我的对象有更多键,例如:

[{
  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 ,遍历它们并使用过滤器和映射对它们进行分组

let 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"
    }];

//grab unique
let distinct = [...new Set(data.map(a => a.id))];

let grouped = distinct.map(d => {
    let filtered=data.filter(d1 => d1.id === d);
    return {
        id: d,
        name: filtered.map(d2 => d2.name)[0],
        value: [...new Set(filtered.map(d2 => d2.value))],
        type: [...new Set(filtered.map(d2 => d2.type))]
    }
});
console.log(grouped);

想法是按 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>