Mauro74
Mauro74

Reputation: 4826

JavaScript find matching object in an array of objects

Hi I have an array of objects

[
       {
         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...
]

Then I'm creating another object

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

And I want to find if the new created object matches any of the object in the array. I tried this with no luck

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

Any idea?

Thanks in advance

Upvotes: 0

Views: 305

Answers (3)

W.D.
W.D.

Reputation: 1041

If I've understood your question correctly, you want something like this 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));

Upvotes: 1

Silz
Silz

Reputation: 256

linking: Check this http://jsfiddle.net/taN4Z/ //checking new array values within old one

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

Here obj2 ( new array ) values are checked with the old array ( obj1 ) values .

Upvotes: -1

Cerbrus
Cerbrus

Reputation: 72957

Try this:

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

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

This assumes the object you're looking for is stored in a search variable:

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

Upvotes: 2

Related Questions