Find value in javascript array of objects deeply nested with ES6

后端 未结 4 2066
星月不相逢
星月不相逢 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:34

    First, your function could be improved by halting once a match is found via the recursive call. Also, you're both declaring match outside, as well as returning it. Probably better to just return.

    const findMatchRecursion = (activity, activityItems) => {
        for (let i = 0; i < activityItems.length; i += 1) {
            if (activityItems[i].activity === activity) {
                return true;
            }
    
            if (activityItems[i].items && findMatchRecursion(activity, activityItems[i].items) {
                return true;
            }
        }
    
        return false;
    };
    

    There's no built in deep search, but you can use .find with a named function if you wish.

    var result = !!activityItems.find(function fn(item) {
      return item.activity === "Gym" || (item.items && item.items.find(fn));
    });
    

提交回复
热议问题