首页 > 解决方案 > 迭代嵌套数组,es6方式,我已经使用foreach完成了

问题描述

我已经使用 forEach 完成了迭代,代码正在运行,但请你建议它是否可以以 es6 方式完成,并且我的实现是否正确

我已经完成了迭代,代码可以工作,但是我想知道更流畅的方法以及这种实现是否正确

  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)

标签: javascriptarraysjavascript-objects

解决方案


ES6 方法是首先将数组映射到您只感兴趣的值。然后使用someArray 方法查找是否有任何项目通过您的条件。

indexOf此外,您可以使用includeswhich 返回布尔值来代替。

  const checkBoolean = arrayToBeChecked
    .map(({ objectvalue }) => [...objectvalue.first, objectvalue.second ])
    .some(v => v.includes('valueIamLookingFor'));


推荐阅读