我不确定是否已有此功能,我需要的是以下内容 反应中的json,我需要这个来搜索城市是否重复并且只返回一个结果, 例如,如果我有5柏林,只有第一个柏林返回 如果我有5加利福尼亚州,第一个加利福尼亚州返回
[
{id:1, city: "berlin"},
{id:2, city: "berlin"},
{id:3, city: "berlin"},
{id:5, city: "california"},
{id:6, city: "california"},
{id:7, city: "california"}
]
感谢您的帮助
答案 0 :(得分:1)
const arr = [{"id":1,"city":"berlin"},{"id":2,"city":"berlin"},{"id":3,"city":"berlin"},{"id":5,"city":"california"},{"id":6,"city":"california"},{"id":7,"city":"california"}];
const result = arr.filter(function({ city }) {
return this.has(city) ? false : this.add(city);
}, new Set);
console.log(result);

或reduce数组到Map按国家/地区,spread返回数组:
const arr = [{"id":1,"city":"berlin"},{"id":2,"city":"berlin"},{"id":3,"city":"berlin"},{"id":5,"city":"california"},{"id":6,"city":"california"},{"id":7,"city":"california"}];
const result = [...arr.reduce((m, o) => m.has(o.city) ? m : m.set(o.city, o), new Map).values()];
console.log(result);