gpt4 book ai didi

Javascript 对象数组和唯一值

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

我有一个看起来像这样的对象数组:

[
{"name":"Andrea","from":"USA","Food":"Candy"},
{"name":"Matt","from":"Taiwan","Food":"Chicken"},
{"name":"Roddy","from":"USA","Food":"Rice"},
{"name":"Andy","from":"Great Britain","Food":"Steak"},
];

有没有办法从上面的数组中获取所有国家的列表,并去掉重复的?

所以从上面的列表中,我要获取的列表是:

["USA", "Taiwan", "Great Britain"]

谢谢!

最佳答案

只需遍历 people 并在新数组中插入独特的国家/地区。这是一个例子。

var countries = [];

var people = [
{"name":"Andrea","from":"USA","Food":"Candy"},
{"name":"Matt","from":"Taiwan","Food":"Chicken"},
{"name":"Roddy","from":"USA","Food":"Rice"},
{"name":"Andy","from":"Great Britain","Food":"Steak"},
];

for (var i = 0, l=people.length; i < l; i++) {
if(people[i] && people[i].from) {//ensure country exists
if (countries.indexOf(people[i].from) == -1) {//ensure unique
countries.push(people[i].from);
}
}
}

关于Javascript 对象数组和唯一值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29168795/

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