JavaScript在对象数组中查找匹配对象

时间:2014-06-03 09:05:14

标签: javascript jquery arrays

嗨,我有一个对象数组

[
       {
         outletId: 619734
         tleaderId: "3f8be9bf-5920-4d3d-b915-50ca76cb21oo"
       },
       {
         outletId: 619755
         tleaderId: "3f8be9bf-5920-4d3d-b915-50ca76cb24ty"   
       },
       {
         outletId: 619700
         tleaderId: "3f8be9bf-5920-4d3d-b915-50ca76cb2qwe"  
       }
       // and so on...
]

然后我创建了另一个对象

[
       {
         outletId: 619734
         tleaderId: "3f8be9bf-5920-4d3d-b915-50ca76cb21oo"
       }
]

我想找到新创建的对象是否与数组中的任何对象匹配。我试了这个没有运气

$.each(objCollection, function () {
      if (this === newObject) {
         alert("Already exist!!!");
      }
});

有什么想法吗?

提前致谢

3 个答案:

答案 0 :(得分:2)

试试这个:

var exists = array.some(function(obj){
    return obj.outletId == search.outletId && obj.tleaderId == search.tleaderId;
});

if(exists){
    alert("Already exist!!!");
}

这假设您要查找的对象存储在search变量中:

var search = {
    outletId: 619734
    tleaderId: "3f8be9bf-5920-4d3d-b915-50ca76cb21oo"
}

答案 1 :(得分:1)

如果我已正确理解您的问题,您需要这样的内容DEMO

var array = [{
    outletId: 619734,
    tleaderId: "3f8be9bf-5920-4d3d-b915-50ca76cb21oo"
}, {
    outletId: 619755,
    tleaderId: "3f8be9bf-5920-4d3d-b915-50ca76cb24ty"
}, {
    outletId: 619700,
    tleaderId: "3f8be9bf-5920-4d3d-b915-50ca76cb2qwe"
}
// and so on...
]

var newArray = [{
    outletId: 619734,
    tleaderId: "3f8be9bf-5920-4d3d-b915-50ca76cb21oo"
}];

function matchCase(array1,array2){

    var matchFound = false;

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

        item = array1[i];

        if (item.outletId === array2[0].outletId && item.tleaderId === array2[0].tleaderId) {

            matchFound = true;
            break;

        }
    }

    return matchFound;

}

console.log(matchCase(array,newArray));

答案 2 :(得分:-1)

关联:检查此http://jsfiddle.net/taN4Z/ //检查旧数组中的新数组值

    $.each(obj2, function (key1,val1) {
      $.each(obj1, function (key2,val2) {
        if(val1.outletId==val2.outletId){
           alert("Already exist!!!"+val1.outletId);
        }
     });     
   });

这里使用旧数组(obj1)值检查obj2(新数组)值。