美文网首页
Js 递归查找数组中指定条件的一组对象

Js 递归查找数组中指定条件的一组对象

作者: 码农界四爷__King | 来源:发表于2020-11-18 15:05 被阅读0次

    需求:在多维数组中查找指定条件的对象,且取出该对象内容数据;数组数据格式如下:

    image

    实现:方法一:

     // 递归查找
                getParentId(list, iid) {
                    for(let o of list || []) {
                        if(o.category_id == iid) return o
                        const o_ = this.getParentId(o.children, iid)
                        if(o_) return o_
                    }
                },
            
                // 使用输入结果
                groupChange(e) {
                    var item = this.getParentId(this.categoryList, e)
                    console.log(item) // 即item 是需要的结果内容
                },
    

    方法二:

                          /**
                 * 递归获取item数据
                 * 1. 递归数组,判断内部有没有children属性,如果有的话,再次进入循环 
                 * */
                recursive(id, obj) {
                    var result = {} // 也可以是全局声明的变量
                    obj.forEach(item => {
                        if (item.category_id == id) {
                            result = item
                        }
                        
                        if (item.children) {
                            this.recursive(id, item.children)
                        }
                    })
                    return result
                }
            
                // 使用结果
                GroupChange(e) {
                     var result = this.recursive(e, this.categoryList)
                     console.log(result)
                },
    

    方法三,

    function findBFS(objects, id) {
      const queue = [...objects]
      while (queue.length) {
        const o = queue.shift()
        if (o.uid== id) return o
        queue.push(...(o.children || []))
      }
    }
    

    其他:适用于没有子代的简单数组.

    需要一个函数,或者一个lodash模块,它可以递归搜索整个数组并返回对象(数组中的项)

    findContainingObject(array, uuid) {
        let result = [];
        result = array.filter( item => {
            return item.uuid === uuid
        })
        return result;
    }
    

    以上内容仅供参考使用!

    相关文章

      网友评论

          本文标题:Js 递归查找数组中指定条件的一组对象

          本文链接:https://www.haomeiwen.com/subject/tdeciktx.html