search

Home  >  Q&A  >  body text

Check for a value in an array of objects

function weatherCodes(){
let codes = [{sunny:[1001]},{cloudy:[1002,1003]}]
let theCode = 1003
};

How do I check my array of objects to find if one of them contains my variable theCode

P粉176151589P粉176151589526 days ago484

reply all(1)I'll reply

  • P粉517475670

    P粉5174756702023-09-10 00:39:21

    Using flat() and includes() Simple reference provided for you

    function weatherCodes(){
      let codes = [{sunny:[1001]},{cloudy:[1002,1003]}]
      let theCode = 1003
      return codes.some(c => Object.values(c).flat().includes(theCode));
    };
    
    console.log(weatherCodes());


    Another option

    function weatherCodes(){
      let codes = [{sunny:[1001]},{cloudy:[1002,1003]}]
      let theCode = 1003
      let values = codes.flatMap(c => Object.values(c)).flat()
      return values.includes(theCode)
    };
    
    console.log(weatherCodes());

    reply
    0
  • Cancelreply