Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find whether object exist in array or not javascript

I have an array of objects in javascript. Something similar to this :

    var objectArray = [
         { "Name" : "A", "Id" : "1" },
         { "Name" : "B", "Id" : "2" },
         { "Name" : "C", "Id" : "3" },
         { "Name" : "D", "Id" : "4" }
    ];

Now i am trying to find out whether an object with a given property Name value exist in the array or not through in built function like inArray, indexOf etc. Means if i have only a string C than is this possible to check whether an obejct with property Name C exist in the array or not with using inbuilt functions like indexOf, inArray etc ?

like image 463
user1740381 Avatar asked Nov 03 '12 08:11

user1740381


3 Answers

Rather than use index of, similar to the comment linked answer from Rahul Tripathi, I would use a modified version to pull the object by name rather than pass the entire object.

function pluckByName(inArr, name, exists)
{
    for (i = 0; i < inArr.length; i++ )
    {
        if (inArr[i].name == name)
        {
            return (exists === true) ? true : inArr[i];
        }
    }
}

Usage

// Find whether object exists in the array
var a = pluckByName(objectArray, 'A', true);

// Pluck the object from the array
var b = pluckByName(objectArray, 'B');
like image 182
David Barker Avatar answered Oct 13 '22 10:10

David Barker


var found = $.map(objectArray, function(val) {
    if(val.Name == 'C' ) alert('found');
});​

Demo

like image 42
Sibu Avatar answered Oct 13 '22 10:10

Sibu


You could try:

objectArray.indexOf({ "Name" : "C", "Id" : "3" });

A better approach would be to simply iterate over the array, but if you must use indexOf, this is how you would do it.

The iteration approach would look like:

var inArray = false;
for(var i=0;i<objectArray.length;i++){
    if(objectArray[i]["Name"] == "C"){
        inArray = true;
    }
}
like image 37
Asad Saeeduddin Avatar answered Oct 13 '22 10:10

Asad Saeeduddin