gpt4 book ai didi

javascript - 从对象数组中获取唯一的对象

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

我有一个如下所示的对象数组:

[
{
"places": "NEW YORK",
"locations": "USA"
},
{
"places": "MONTREAL",
"locations": "QUEBEC",
"country": "Canada"
},
{
"places": "MONTREAL",
"locations": "QUEBEC",
"country": "Canada"
}
]

我想过滤并仅获取唯一的条目。我尝试了以下功能,但不起作用:

function onlyUnique(value, index, self) { 
return self.indexOf(value) === index;
}

使用Set似乎也不起作用。有什么想法吗?

最佳答案

使用new Set()的简单解决方案。

const data = [
{
"places": "NEW YORK",
"locations": "USA"
},
{
"places": "MONTREAL",
"locations": "QUEBEC",
"country": "Canada"
},
{
"places": "MONTREAL",
"locations": "QUEBEC",
"country": "Canada"
},

];

const uniqueArray = a => [...new Set(a.map(o => JSON.stringify(o)))].map(s => JSON.parse(s));

console.log(uniqueArray(data));

关于javascript - 从对象数组中获取唯一的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55523596/

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