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 ?
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');
var found = $.map(objectArray, function(val) {
if(val.Name == 'C' ) alert('found');
});
Demo
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With