How to find if an object has a value?
My Object looks like below: I have to loop through the object array and check if an array has “SPOUSE” in its value. if exist set a flag spouseExits = true
and store the number (in this case (4 because [SPOUSE<NUMBER>] NUMBER is 4) in a variable 'spouseIndex'
This function needs to render in IE9 as well.
JavaScript
x
12
12
1
eligibilityMap = {
2
"CHIP": [
3
"CHILD5"
4
],
5
"APTC/CSR": [
6
"SELF1",
7
"CHILD2",
8
"CHILD3",
9
"SPOUSE4"
10
]
11
}
12
Code:
JavaScript
1
12
12
1
Object.keys(eligibilityMap).reduce(function (acc, key) {
2
const array1 = eligibilityMap[key];
3
//console.log('array1', array1);
4
array1.forEach(element => console.log(element.indexOf('SPOUSE')))
5
var spouseExist = array1.forEach(function (element) {
6
//console.log('ex', element.indexOf('SPOUSE') >= 0);
7
return element.indexOf('SPOUSE') >= 0;
8
});
9
//console.log('spouseExist', spouseExist);
10
return acc;
11
}, {});
12
SpouseIndex is undefined. What am I doing wrong?
Advertisement
Answer
Here’s a simple approach, supports in all browsers including IE:
JavaScript
1
16
16
1
var spouseExists = false;
2
var spouseNumber;
3
for(var key in eligibilityMap)
4
{
5
for(var index in eligibilityMap[key])
6
{
7
if (eligibilityMap[key][index].indexOf("SPOUSE") > -1)
8
{
9
spouseExists = true;
10
spouseNumber = eligibilityMap[key][index].replace("SPOUSE", '');
11
break;
12
}
13
}
14
}
15
console.log(spouseExists, spouseNumber);
16