8

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 ?

user1740381
  • 2,121
  • 8
  • 37
  • 61

4 Answers4

9

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');
David Barker
  • 14,484
  • 3
  • 48
  • 77
8
var found = $.map(objectArray, function(val) {
    if(val.Name == 'C' ) alert('found');
});​

Demo

Sibu
  • 4,609
  • 2
  • 26
  • 38
1

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;
    }
}
Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139
0

Well, if the object is not too big, you can consider iterate and match to find if the particular object exist like below:

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


//Function to check if object exist with the given properties
function checkIfObjectExist(name,id)
{
for(var i=0;i<objectArray.length;i++)
 {
  if(objectArray[i].Name===name && objectArray[i].Id===id)
   {     
      return true;
   }
 }    
}

// Test if function is working
console.log(checkIfObjectExist("B","2"));
Sunny Sharma
  • 4,688
  • 5
  • 35
  • 73