Find value in javascript array of objects deeply nested with ES6

后端 未结 4 2065
星月不相逢
星月不相逢 2021-01-12 10:46

In an array of objects I need to find a value -- where key is activity : However the activity key can be dee

4条回答
  •  一生所求
    2021-01-12 11:35

    You can use some() method and recursion to find if activity exists on any level and return true/false as result.

    const activityItems = [{"name":"Sunday","items":[{"name":"Gym","activity":"weights"}]},{"name":"Monday","items":[{"name":"Track","activity":"race"},{"name":"Work","activity":"meeting"},{"name":"Swim","items":[{"name":"Beach","activity":"scuba diving"},{"name":"Pool","activity":"back stroke"}]}]}]
    
    let findDeep = function(data, activity) {
      return data.some(function(e) {
        if(e.activity == activity) return true;
        else if(e.items) return findDeep(e.items, activity)
      })
    }
    
    console.log(findDeep(activityItems, 'scuba diving'))

提交回复
热议问题