Search code examples
javascriptarraysjavascript-objects

Iterating over nested array , the es6 way, I have already done using foreach


I have done the iteration using forEach ,code is working but please could you suggest if it can be done in es6 way and is my implementation correct or not

I have done the iteration , the code works ,however I wanted to know more sleek way of doing it and whether this implementation is correct

  var arrayToBeChecked = 
          [
            { name: "one",
              objectvalue : {
                        first : ['valueIamNotInterestedIn0'],
                        second :'valueIamNotInterestedIn1'
                       }
             },
             { name: "two",
               objectvalue : {
                        first : ['valueIamLookingFor'],
                        second :'valueIamNotInterestedIn5'
                       }
             },
             { name: "three",
               objectvalue : {
                        first : ['valueIamNotInterestedIn5'],
                        second :'valueIamNotInterestedIn5'
                       }
             }

          ]

   var checkBoolean = false;

   arrayToBeChecked.forEach(val => {
    let selectedArray =  val.objectvalue['first']
      if(selectedArray.indexOf('valueIamLookingFor') > -1){
         checkBoolean = true 
      }
   })

   console.log(checkBoolean)

Solution

  • Your current approach is not that efficient because you'll keep iterating even after you find a match. For this kind of check (see if any of the values of the array match a condition) you can use .some(...)

    Here is an example:

    var arrayToBeChecked = [{
        name: "one",
        objectvalue: {
          first: ['valueIamNotInterestedIn0'],
          second: 'valueIamNotInterestedIn1'
        }
      },
      {
        name: "two",
        objectvalue: {
          first: ['valueIamLookingFor'],
          second: 'valueIamNotInterestedIn5'
        }
      },
      {
        name: "three",
        objectvalue: {
          first: ['valueIamNotInterestedIn5'],
          second: 'valueIamNotInterestedIn5'
        }
      }
    
    ];
    
    const result = arrayToBeChecked.some(({
      objectvalue: {
        first
      }
    }) => first.includes('valueIamLookingFor'));
    
    console.log(result);