[英]Check if value exists in JavaScript object
How would I check in my array of objects, if a specific item exists (in my case MachineId with id 2)? 如果存在特定项目(在我的情况下,机箱ID为id 2),我将如何检查我的对象数组?
[{"MachineID":"1","SiteID":"20"},{"MachineID":"2","SiteID":"20"},{"MachineID":"3","SiteID":"20"},{"MachineID":"4","SiteID":"20"}]
I tried this: 我试过这个:
if (index instanceof machineIds.MachineID) {
alert('value is Array!');
} else {
alert('Not an array');
}
In cross browser way you may use jQuery.grep()
method for it: 在跨浏览器方式中,您可以使用
jQuery.grep()
方法:
var item = $.grep(machineIds, function(item) {
return item.MachineID == index;
});
if (item.length) {
alert("value is Array!");
}
The simplest to understand solution is to loop over the array, and check each one. 最简单易懂的解决方案是循环遍历数组,并检查每个数组。
var match;
for (var i = 0; i < yourArray.length; i++) {
if (yourArray[i].MachineId == 2)
match = yourArray[i];
}
Note if there is more than one matching item, this will return the last one. 请注意,如果有多个匹配项,则返回最后一个。 You can also dress this up in a function.
你也可以在一个功能中打扮。
function findByMachineId(ary, value) {
var match;
for (var i = 0; i < ary.length; i++) {
if (ary[i].MachineId == value)
match = ary[i];
}
return match;
}
There are many standard solution, you don't need third party libraries or loop iteratively. 有许多标准解决方案,您不需要第三方库或迭代循环。
some
method - since JavaScript 1.6. some
方法 - 从JavaScript 1.6开始。 find
method - since ES6 find
方法 - 自ES6以来 findIndex
method - since ES6 findIndex
方法 - 自ES6以来 For example, using some()
; 例如,使用
some()
;
var yourArray = [{"MachineID":"1","SiteID":"20"},{"MachineID":"2","SiteID":"20"},{"MachineID":"3","SiteID":"20"},{"MachineID":"4","SiteID":"20"}];
var params = {searchedID: "2", elementFound: null};
var isCorrectMachineID = function(element) {
if (element.MachineID == this.searchedID);
return (this.elementFound = element);
return false;
};
var isFound = yourArray.some(isCorrectMachineID, params)
Array some
method accepts two parameters: 数组
some
方法接受两个参数:
Callback function is not coupled with the iteration code and, using thisObject parameter, you can even return to the caller the element found or more data. 回调函数不与迭代代码耦合,使用thisObject参数,您甚至可以返回调用者找到的元素或更多数据。 If such an element is found,
some
immediately returns true 如果找到这样的元素,
some
立即返回true
Old question at this point, but here's an ES6 solution that uses Array.find : 此时的老问题,但这是一个使用Array.find的ES6解决方案:
let machine2 = machines.find((machine) => machine.id === '2');
if (machine2) {
// ...
}
你可以使用这个条件:
if (arr.filter(function(v){return this.MachineID == 2;}).length > 0)
var item = [{"MachineID":"1","SiteID":"20"},{"MachineID":"2","SiteID":"20"},{"MachineID":"3","SiteID":"20"},{"MachineID":"4","SiteID":"20"}];
var newItem = item.filter(function(i) {
return i.MachineID == 2; //it will return an object where MachineID matches with 2
});
console.log(newItem); // will print [{"MachineID":"2","SiteID":"20"}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.