Javascript 如何使用Lodash搜索和筛选嵌套属性?
我有一个形状像这样的物体:Javascript 如何使用Lodash搜索和筛选嵌套属性?,javascript,lodash,Javascript,Lodash,我有一个形状像这样的物体: const config = [ { id: 'foo', props, }, { id: 'bar', props, children: [ { id: 'bat', props, }, { id: 'baz', props, children: [ { /
const config = [
{
id: 'foo',
props,
},
{
id: 'bar',
props,
children: [
{
id: 'bat',
props,
},
{
id: 'baz',
props,
children: [
{
// this is the object I want to access
id: 'qux',
props,
},
]
},
],
},
]
我需要使用config
数组上的某种“.deep
”(递归?)过滤器来访问id
属性为qux
的对象。或者某种“.plant
”,然后是“.filter
”组合模式
如何使用Lodash实现这一点?您可以使用带有递归的纯js和一些方法来实现这一点,这些方法将循环数组并在第一次匹配时退出,如
some
const-config=[{“id”:“foo”,“props”:1},{“id”:“bar”,“props”:1,“children”:[{“id”:“bat”,“props”:1},{“id”:“baz”,“props”:1,“children”:[{“id”:“qux”,“props”:“target prop”,}]
函数查找(数据,id){
设result=null;
数据部分(e=>{
如果(e.id==id)返回结果=e;
如果(!result&&e.children)result=find(e.children,id)
})
返回结果;
}
const result=find(配置'qux')
console.log(result)
这是一个不含lodash或任何其他包的普通ES6解决方案。简单地展平您的原始结构(我使用了一个简单的递归函数,它利用了-但是还有其他方法可以展平),然后使用它来获得所需的元素
例如(我用一些虚假数据将数组嵌套得更深,只是为了表明无论子项的深度有多深,
都可以继续:
const-props='Default-props-data..';
常量配置=[{
id:‘foo’,
道具,
}, {
id:'酒吧',
道具,
儿童:[{
id:'蝙蝠',
道具,
}, {
id:'baz',
道具,
儿童:[{
id:'qux',
道具:“这是曲棍球道具”,
儿童:[{
id:‘abc’,
道具:“这是abc道具”,
儿童:[{
id:‘bcd’,
道具:“这是bcd道具”
}]
}]
}]
}]
}];
//创建一个漂亮的单层结构的函数
常数展平=arr=>{
返回arr.reduce((累计,el)=>{
累积推力({
id:el.id,
道具:el.props
});
如果(儿童){
累加=累加concat(展平(el.children));
}
返回累计;
}, []);
};
//在展平数组中通过ID查找所需元素的函数
const getElById=(arr,id)=>flatten(arr).find(el=>el.id==id);
log(getElById(配置'qux'))
log(getElById(配置'abc'))
console.log(getelbyd(config,'bcd'))
+1。我也非常感谢这个答案。我希望我们能接受两个答案,这样我也能接受你的答案。别担心,很高兴它有用!