我有一个JSON数组如下:
[{
"Id": "1",
"Name": "A"
}, {
"Id": "2",
"Name": "B"
}, {
"Id": "3",
"Name": "C"
}, {
"Id": "4",
"Name": "B"
}, {
"Id": "5",
"Name": "D"
}, {
"Id": "6",
"Name": "E"
}, {
"Id": "7",
"Name": "C"
}, {
"Id": "8",
"Name": "D"
}]
我想找出ID重复的ID。例如从上面的数组我应该得到一个返回重复名称ID的数组。
2 3 4 五 7 8
因为B,C,D在循环中出现不止一次。
答案 0 :(得分:1)
var myArray = [{
"Id": "1",
"Name": "A"
}, {
"Id": "2",
"Name": "B"
}, {
"Id": "3",
"Name": "C"
}, {
"Id": "4",
"Name": "B"
}, {
"Id": "5",
"Name": "D"
}, {
"Id": "6",
"Name": "E"
}, {
"Id": "7",
"Name": "C"
}, {
"Id": "8",
"Name": "D"
}];
var repeat_ids=[];
for(var key1 in myArray){
var exists_name_len = $.map(myArray, function(n, i) {if(n.Name==myArray[key1].Name){ return i; }}).length;
if(exists_name_len>1){repeat_ids.push(myArray[key1].Id);}
}
console.log(repeat_ids);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
答案 1 :(得分:0)
你的阵列:
var myArray = [{
"Id": "1",
"Name": "A"
}, {
"Id": "2",
"Name": "B"
}, {
"Id": "3",
"Name": "C"
}, {
"Id": "4",
"Name": "B"
}, {
"Id": "5",
"Name": "D"
}, {
"Id": "6",
"Name": "E"
}, {
"Id": "7",
"Name": "C"
}, {
"Id": "8",
"Name": "D"
}]
var arr = [];
for(var i = 0; i < myArray.length ; i++ ){
var obj = myArray[i];
if(arr[obj.id] >= 0)
{
myArray.push(i);
i--;
}
arr[obj.id] = i;
}