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
6 Answers 6
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.
Comments
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.
Comments
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?
Comments
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.
Comments
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
Comments
Nowadays you can also use Includes.
if(watchesArray[0].sports.includes('Running'))
{
// Exists
}
else{
// Doesn't exist
}
This is not always supported though so check that you browser supports it.
watchesArray[0].sports.indexOf('Running') !== -1Note that this returns0if it's the first index, so you have to check for-1(which is "not found").