[英]How to find whether object exist in array or not javascript
I have an array of objects in javascript. 我在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 ? 现在我试图找出一个具有给定属性
Name
值的对象是否存在于数组中,或者不是通过内置函数,如inArray
, indexOf
等。意味着如果我只有一个字符串C
,那么可以检查是否有一个obejct与属性名称C是否存在于数组中或不使用内置函数,如indexOf,inArray等?
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. 与使用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];
}
}
}
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');
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. 更好的方法是简单地遍历数组,但如果必须使用indexOf,那么就是这样做的。
The iteration approach would look like: 迭代方法看起来像:
var inArray = false;
for(var i=0;i<objectArray.length;i++){
if(objectArray[i]["Name"] == "C"){
inArray = true;
}
}
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"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.