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

您所在的位置:网站首页 js数组中查找元素 Js 递归查找数组中指定条件的一组对象;

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

2024-07-15 04:12| 来源: 网络整理| 查看: 265

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

实现:方法一:

// 递归查找 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; }

以上内容仅供参考使用!



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3