如何查找对象是否存在于数组中或不存在javascript [英] How to find whether object exist in array or not javascript

查看:160
本文介绍了如何查找对象是否存在于数组中或不存在javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在javascript中有一个对象数组。类似于:

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

现在我试图找出具有给定属性的对象名称数组中是否存在值,或者不存在于内置函数中,如 inArray indexOf 等。意味着如果我只有一个字符串 C ,那么可以通过使用内置函数(如indexOf,inArray等)检查数组中是否存在具有属性名称C的obejct?

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的评论链接答案,我会使用修改后的版本拉取对象按名称而不是传递整个对象。

Rather than use index of, similar to the comment linked answer from Rahul Tripat 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];
        }
    }
}

用法

// Find whether object exists in the array
var a = pluckByName(objectArray, 'A', true);

// Pluck the object from the array
var b = pluckByName(objectArray, 'B');

这篇关于如何查找对象是否存在于数组中或不存在javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆