[英]grep returning undefined when trying to access object in array
I have an array have built up with a series of objects in it, but when i am trying to use grep to bring back just one object based on a condition, it is always returning undefined 我有一个数组,其中包含一系列对象,但是当我尝试使用grep根据条件带回一个对象时,它总是返回未定义的
Array is like 数组就像
[Object { Id=61, Name=”A Name”, Department=”A Department”, Tag=”A Tag”}, Object {Id=62....
Now the id i am passing in, is not the index, it is the actual Id of the object..ie: 61 现在我要传递的ID不是索引,而是对象的实际ID。即:61
var resultOut = $.grep(myArray, function (e) {
return e.Id === id;
});
console.log(resultOut[0]);
Now it has been mentioned that it may be because it is changing the id i am passing in as a string, so the e.Id === id does not match, ut i have no way of checking this 现在已经提到,可能是因为它正在更改我以字符串形式传递的id,所以e.Id === id不匹配,但我无法检查此
If it's id
being a string, two ways to fix it. 如果
id
是字符串,则有两种方法可以修复它。 Use ==
: 使用
==
:
return e.Id == id;
Or convert id
to int: 或将
id
转换为int:
return e.Id === +id;
// ^
The +
before id
is equivalent to a parseInt()
. id
之前的+
等效于parseInt()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.