jQuery - 在对象数组中查找不同的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7431618/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:50:53  来源:igfitidea点击:

jQuery - Finding Distinct Values in Object Array

jquery

提问by Dexter

I've got an array of objects where each object has fields like title, description, family, etc. How can I perform a jQuery operation that grabs all objects in this array with a unique family name - similar to SQL's DISTINCT clause?

我有一个对象数组,其中每个对象都有标题、描述、系列等字段。我如何执行 jQuery 操作来获取该数组中具有唯一系列名称的所有对象 - 类似于 SQL 的 DISTINCT 子句?

回答by Nicola Peluchetti

You could do:

你可以这样做:

var array = [{
    familyName: "one"},
{
    familyName: "two"},
{
    familyName: "one"},
{
    familyName: "two"}];

var dupes = {};
var singles = [];

$.each(array, function(i, el) {

    if (!dupes[el.familyName]) {
        dupes[el.familyName] = true;
        singles.push(el);
    }
});

Singles is an array with only DISTINCT objects

Singles 是一个只有 DISTINCT 对象的数组

EDIT - i have blogged about this and given a more elaborate answer http://newcodeandroll.blogspot.it/2012/01/how-to-find-duplicates-in-array-in.html

编辑 - 我已经写了关于这个的博客并给出了一个更详细的答案http://newcodeandroll.blogspot.it/2012/01/how-to-find-duplicates-in-array-in.html