Javascript对象数组和唯一值

时间:2015-03-20 14:23:05

标签: javascript arrays

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

[
{"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"]

谢谢!

4 个答案:

答案 0 :(得分:4)

只需循环遍历人员并在新数组中插入唯一的国家/地区。这是一个例子。

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);
        }
    }
}

答案 1 :(得分:3)

reduce

的另一种变体
var arr = [
    {"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"},
];

var countries = arr.reduce(function(acc, cur){
                    if(!acc.map[cur.from]){
                        acc.map[cur.from]=true;
                        acc.result.push(cur.from);
                    }
                    return acc;
                }, {result:[], map:{}}).result;

&#13;
&#13;
var arr = [
    {"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"},
];

var countries = arr.reduce(function(acc, cur){
                    if(!acc.map[cur.from]){
                        acc.map[cur.from]=true;
                        acc.result.push(cur.from);
                    }
                    return acc;
                }, {result:[], map:{}}).result;

document.getElementById('countries').innerHTML = countries.join();
&#13;
<span id="countries"></span>
&#13;
&#13;
&#13;

答案 2 :(得分:2)

如果您已经使用了优秀的Lodash库,以下内容将在一行中整齐地为您完成:

var uniqueCountries = _(dataArray).pluck('from').unique().value();

UnderscoreJS使用链接具有类似的功能。

对于D3.js,以下将执行此操作:

var uniqueCountries = d3.set(dataArray.map(function (x) { return x.from; })).values();

如果不对服务器执行unique-ifying并单独返回该数据,则无法绕过所有记录至少一次来执行此操作。但是,对于1000条左右的记录,这仍然会非常快。 对于普通的JS,请参阅其他答案。

答案 3 :(得分:1)

我遍历数组并将国家/地区放入数组中,如果它还不在该数组中。