How can I check If a nested array contains a value

2020-04-20 08:24发布

问题:

So I have this array:

   var watchesArray = [
        {
          model: "FR 10", 
          image:"",
          url: "",
          price: 129.99,
          sports: ["Running", "Fitness"],
          touchScreen:false,
          GPS:false,
          heartRateMonitor:false,
          hrZoneTraining:false,
        },
    ];

    if(watchesArray[0].sports(contains a specific value or values){
      do something
    } else {
       dont do anything
    }

And all I want to do is check whether this watch has a specific sport and if it does then put it in an if statement so that I can do something with it.

How can I do this? Thanks

回答1:

Use Array.indexOf like bellow

if(watchesArray[0].sports.indexOf('Running') > -1){
    do somwthing
}

NOTE:- In case of if parents doesn't exist it'll throw error.



回答2:

It's just an array, even if it's "nested":

if (watchesArray[0].sports.indexOf('Running') !== -1) ...

This returns 0 if it's the first index, so you have to check for -1 (which is "not found").

Note that IE7/8 did not support Array.prototype.indexOf(), but there are ways to polyfill that if needed.



回答3:

There is no one simple function which supported in all browsers but you can write the following code:

function contains(a, obj) {
    var i = a.length;
    while (i--) {
       if (a[i] === obj) {
           return true;
       }
    }
    return false;
}

For more details you look in this answer How do I check if an array includes an object in JavaScript?



回答4:

You can try indexof like this:

var watchesArray = [
                     {
                       model: "FR 10", 
                       image:"",
                       url: "",
                       price: 129.99,
                       sports: ["Running", "Fitness"],
                       touchScreen:false,
                       GPS:false,
                       heartRateMonitor:false,
                       hrZoneTraining:false,
                     },
                 ];

 if (watchesArray[0].sports.indexOf('hello') != -1){
                     alert("exists");
                 } else {
                     alert("this index does not exist");
                 }

for array in javascript you can always traverse using the key specified. if the key does not exists indexof will return 0 so it will go to the else part.



回答5:

As Jared mentioned you can use Array.indexOf()

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

In your case it would mean

if(watchesArray[0].sports.indexOf(value) !== -1){
  do something
} else {
   dont do anything
}

I also provided you a little function to match multiple values: jsbin