[英]How to pass a property from an array to each of it nested child array with lodash?
[英]lodash property search in array and in nested child arrays
我有这个数组:
[
{
id: 1,
name: 'test 1',
children: []
},
{
id: 2,
name: 'test 2',
children: [
{
id: 4,
name: 'test 4'
}
]
},
{
id: 3,
name: 'test 3',
children: []
}
]
如何通过此数组和嵌套children
数组中的id
属性进行过滤?
例如,搜索id = 3
,应返回test 3
对象,搜索id = 4
应返回test 4
对象。
使用 lodash,您可以执行以下操作:
_(data)
.thru(function(coll) {
return _.union(coll, _.map(coll, 'children') || []);
})
.flatten()
.find({ id: 4 });
在这里, thru()用于初始化包装值。 它返回原始数组和嵌套子数组的联合。 然后使用flatten() 将这个数组结构展平,以便您可以find()项目。
这是一个非常简单的树遍历任务。 解决它的最简单方法是递归(链接到jsbin )。 它将适用于任何深度(当然有递归限制),并且它是最复杂 O(n) 的最快方法之一:
function find(id, items) {
var i = 0, found;
for (; i < items.length; i++) {
if (items[i].id === id) {
return items[i];
} else if (_.isArray(items[i].children)) {
found = find(id, items[i].children);
if (found) {
return found;
}
}
}
}
要查找所有匹配项 - 稍微修改的函数(上面的 jsbin 链接已更新):
function findAll(id, items) {
var i = 0, found, result = [];
for (; i < items.length; i++) {
if (items[i].id === id) {
result.push(items[i]);
} else if (_.isArray(items[i].children)) {
found = findAll(id, items[i].children);
if (found.length) {
result = result.concat(found);
}
}
}
return result;
}
另一个lodash
选项,带有儿童键和无限深度。
const flattenItems = (items, key) => {
return items.reduce((flattenedItems, item) => {
flattenedItems.push(item)
if (Array.isArray(item[key])) {
flattenedItems = flattenedItems.concat(flattenItems(item[key], key))
}
return flattenedItems
}, [])
}
const item = find(flattenItems(items, 'children'), ['id', 4])
您可以通过使用带有 ES6 语法的纯 javascript 来实现这一点:
.reduce
函数展平数组.find
来搜索你要查找的 id
const arr = [
{
id: 1,
name: 'test 1',
children: []
},
{
id: 2,
name: 'test 2',
children: [
{
id: 4,
name: 'test 4'
}
]
},
{
id: 3,
name: 'test 3',
children: []
}
]
const flattenData = arr.reduce((newArr, arr) => {
const {children, ...rest } = arr;
newArr.push(rest);
return newArr.concat(children)
}, [])
console.log(flattenData.find(d=>d.id===4))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.