如何查找对象是否存在于数组中或不存在javascript

use*_*381 8 javascript jquery

我在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 ?

Dav*_*ker 9

与使用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)


Sib*_*ibu 7

var found = $.map(objectArray, function(val) {
    if(val.Name == 'C' ) alert('found');
});?
Run Code Online (Sandbox Code Playgroud)

演示