我在javascript中有一个对象数组.与此类似的东西:
var objectArray = [
{ "Name" : "A", "Id" : "1" },
{ "Name" : "B", "Id" : "2" },
{ "Name" : "C", "Id" : "3" },
{ "Name" : "D", "Id" : "4" }
];
Run Code Online (Sandbox Code Playgroud)
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 ?
与使用Rahul Tripathi的评论链接答案类似,我会使用修改版本来按名称拉取对象,而不是传递整个对象.
function pluckByName(inArr, name, exists)
{
for (i = 0; i < inArr.length; i++ )
{
if (inArr[i].name == name)
{
return (exists === true) ? true : inArr[i];
}
}
}
Run Code Online (Sandbox Code Playgroud)
用法
// Find whether object exists in the array
var a = pluckByName(objectArray, 'A', true);
// Pluck the object from the array
var b = pluckByName(objectArray, 'B');
Run Code Online (Sandbox Code Playgroud)
var found = $.map(objectArray, function(val) {
if(val.Name == 'C' ) alert('found');
});?
Run Code Online (Sandbox Code Playgroud)