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"}]
}
答案 0 :(得分: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]);
}
这是fiddle。
例如,如果您想要name == "name1"
的所有项目的数组,您只需执行以下操作:
var allName1s = sorted["name1"];
答案 1 :(得分: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);
必备Fiddle
答案 2 :(得分: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>
控制台输出(调试):