Search code examples
javascriptinternet-explorer-9ecmascript-5

Check whether an Object contains a specific value in any of its array


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.

eligibilityMap = {
    "CHIP": [
        "CHILD5"
    ],
    "APTC/CSR": [
        "SELF1",
        "CHILD2",
        "CHILD3",
        "SPOUSE4"
    ]
}

Code:

Object.keys(eligibilityMap).reduce(function (acc, key) {
  const array1 = eligibilityMap[key];
  //console.log('array1', array1);
  array1.forEach(element => console.log(element.indexOf('SPOUSE')))
  var spouseExist = array1.forEach(function (element) {
    //console.log('ex', element.indexOf('SPOUSE') >= 0);
    return element.indexOf('SPOUSE') >= 0;
  });
  //console.log('spouseExist', spouseExist);
  return acc;
}, {});

SpouseIndex is undefined. What am I doing wrong?


Solution

  • Here's a simple approach, supports in all browsers including IE:

        var spouseExists = false;
        var spouseNumber;
        for(var key in eligibilityMap)
        {
          for(var index in eligibilityMap[key])
          {
            if (eligibilityMap[key][index].indexOf("SPOUSE") > -1)
            {
              spouseExists = true;
              spouseNumber = eligibilityMap[key][index].replace("SPOUSE", '');
              break;
            }
          }
        }
        console.log(spouseExists, spouseNumber);