0
var names = [{id:1,name:"name1"}, {id:2,name:"name2"}, {id:3,name:"name1"}, {id:4,name:"name1"}, {id:5,name:"name2"}, {id:6,name:"name3"}]

这是我在 javascript 中的对象数组 - 我正在寻找一种方法来提取所有重复项和具有相同名称属性的个人 - 并将它们放入数组对象中。过滤掉重复的对象是我的主要关注点。如果可以在 jQuery 中做到这一点,那很好。

{
    [{id:1,name:"name1"},{id:3,name:"name1"}{id:4,name:"name1"}]
    [{id:2,name:"name2"},{id:5,name:"name2"}] 
    [{id:6,name:"name3"}]
}
4

3 回答 3

1

你可以这样做:

var names = [{id:1,name:"name1"}, {id:2,name:"name2"}, {id:3,name:"name1"}, {id:4,name:"name1"}, {id:5,name:"name2"}, {id:6,name:"name3"}]

var sorted = {};

for (var i=0; i < names.length; i++) {
    if (!sorted[names[i].name]) {
        sorted[names[i].name] = [];
    }
    sorted[names[i].name].push(names[i]);
}

这是一个小提琴

例如,如果您想要包含 的所有项目的数组name == "name1",您只需执行以下操作:

var allName1s = sorted["name1"];
于 2013-10-18T15:12:35.867 回答
1

Matt Burland 给出的方法是查找重复项的标准方法。我在这里使用它,但同时构建您正在寻找的数组数组。

var names = [{id:1,name:"name1"}, {id:2,name:"name2"}, {id:3,name:"name1"}, {id:4,name:"name1"}, {id:5,name:"name2"}, {id:6,name:"name3"}]

var collector = {};
var sorted = [];
for (var i = 0; i < names.length; ++i) {
    var entry = names[i];
    if (!(entry.name in collector)) {
        collector[entry.name] = [];
        sorted.push(collector[entry.name]);
    }
    collector[entry.name].push(entry);
}
console.dir(collector);
console.dir(sorted);

必备的小提琴

于 2013-10-18T15:22:58.083 回答
0

如果您想将数据排序为有效和重复,我会这样做:

Javascript:

<script type="text/javascript">

var names = [{id:1,name:"name1"}, {id:2,name:"name2"}, {id:3,name:"name1"}, {id:4,name:"name1"}, {id:5,name:"name2"}, {id:6,name:"name3"}]

var parsed_names = parseNames(names);

console.log(parsed_names);

function parseNames(names) 
{
    var parsed_data = [];
    var duplicate_data = [];
    var name_list = [];
    for (var i = 0; i < names.length; i++) {
        if (!inArray(names[i].name, name_list)) {
            parsed_data.push(names[i]);
        } else {
            duplicate_data.push(names[i]);
        }
        name_list.push(names[i].name);
    }
    return {
        'ParsedData': parsed_data,
        'DuplicateData': duplicate_data
    };
}

function inArray(needle, haystack) {
    for (var i = 0; i < haystack.length; i++) {
        if (haystack[i] === needle) {
            return true;
        }
    }
    return false;
}

</script>

控制台输出(调试):

在此处输入图像描述

于 2013-10-18T15:18:11.013 回答