gpt4 book ai didi

javascript - 如何从对象数组中删除重复记录?

转载 作者:行者123 更新时间:2023-11-28 17:12:01 25 4
gpt4 key购买 nike

我在 Javascript 中有这个对象。

[{"col1": 1, "col2": 25},{"col1": 1, "col2": 25},{"col1": 3, "col2": 30}]

如何删除重复记录以获得此结果?

[{"col1": 1, "col2": 25},{"col1": 3, "col2": 30}]

我尝试了下一个逻辑,但不起作用:

[...new Set(myData)]

最佳答案

我最近在另一个答案上读到了这个,我喜欢它,它使用 filter() 的可选参数,该参数在过滤器函数内作为 this 传递。

const input = [
{"col1": 1, "col2": 25},
{"col1": 1, "col2": 25},
{"col1": 3, "col2": 30}
];

let res = input.filter(function({col1, col2})
{
return !this.has(`${col1}-${col2}`) && this.add(`${col1}-${col2}`)
}, new Set());

console.log(res);

关于javascript - 如何从对象数组中删除重复记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54174446/

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