JQuery - 我如何比较两个列表

时间:2013-05-31 19:11:07

标签: javascript jquery

我有一个列表和一个我需要比较的DOM对象并获得不同的值

示例:

lista1 = ["type", "name","visible"] 
lista2 = Object {type: "button", name: "button", class: "buttonBlack", visible: "true", backgroundimage: "null"}

lista2 = Object.keys(list2);

我试试:

for(var i = 0; i<lista1.length;i++)

    $.each(lista2,function(key,val){
        if(lista[i] == val){
         list2.remove(val);
        }      
    });
};

我想得到他们之间不相等的物品

我该怎么做?

预期回报:

["class","backgroundimage"]

3 个答案:

答案 0 :(得分:2)

list1 = ["type", "name","visible"] 
list2 = {type: "button", name: "button", class: "buttonBlack", visible: "true", backgroundimage: "null"}
result = []

$.each(list2, function(k,v){
  if ($.inArray(k, list1) === -1) {
    result.push(k)
  }
})

result
>> ["class", "backgroundimage"]

答案 1 :(得分:1)

var list1 = ["type", "name", "class", "visible", "backgroundimage", "disabled", "value"];
var list2 = {type: "button", name: "button", class: "buttonBlack", visible: "true", backgroundimage: "null"};

list2 = Object.keys(list2);

function arr_diff(a1, a2)
{
  var a=[], diff=[];
  for(var i=0;i<a1.length;i++)
    a[a1[i]]=true;
  for(var i=0;i<a2.length;i++)
    if(a[a2[i]]) delete a[a2[i]];
    else a[a2[i]]=true;
  for(var k in a)
    diff.push(k);
  return diff;
}

console.log(arr_diff(list1, list2));

结果

["disabled", "value"] 

** 基于
Get array of object's keys
JavaScript array difference

DEMO

答案 2 :(得分:0)

lista1 = ["type", "name","visible"] 
lista2 = Object {type: "button", name: "button", class: "buttonBlack", visible: "true", backgroundimage: "null"}

result = [];

for (var prop in lista2) {
   if (lista2.hasOwnProperty(prop) && lista1.indexOf(prop) < 0) {
       result.push(prop);
   }
}

数组result将包含对象中不在数组中的所有属性。