简体   繁体   中英

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)?

[{"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:

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.

For example, using 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:

  • callback - Function to test for each element.
  • thisObject - Object to use as this when executing callback.

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. If such an element is found, some immediately returns true

http://jsfiddle.net/gu8Wq/1/

Old question at this point, but here's an ES6 solution that uses Array.find :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM