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 ?

2

4 Answers 4

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');
Sign up to request clarification or add additional context in comments.

Comments

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

Demo

Comments

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;
    }
}

Comments

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"));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.