[英]How to search and filter for nested property using Lodash?
我有一个形状像这样的物体:
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
的对象。 或者某种“ .flatten
”,然后是“ .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",}]}]}] function find(data, id) { let result = null; data.some(e => { if (e.id == id) return result = e; if (!result && e.children) result = find(e.children, id) }) return result; } const result = find(config, 'qux') console.log(result)
这是一个没有 lodash 或任何其他包的 vanilla ES6 解决方案。 简单地展平你的原始结构(我使用了一个简单的递归函数,它利用了Array.prototype.reduce
- 但还有其他方法可以展平)然后使用Array.prototype.find
来获得你想要的元素。
例如(我用一些虚假数据将数组嵌套得更深,只是为了表明无论children
继续深入多少层,该解决方案都应该有效:
const props = 'Default props data..'; const config = [{ id: 'foo', props, }, { id: 'bar', props, children: [{ id: 'bat', props, }, { id: 'baz', props, children: [{ id: 'qux', props: 'This is qux props', children: [{ id: 'abc', props: 'This is abc props', children: [{ id: 'bcd', props: 'This is bcd props' }] }] }] }] }]; //A function to create a nice, single level structure const flatten = arr => { return arr.reduce((accum, el) => { accum.push({ id: el.id, props: el.props }); if (el.children) { accum = accum.concat(flatten(el.children)); } return accum; }, []); }; //A function to find our desired element by ID within a flattened array const getElById = (arr, id) => flatten(arr).find(el => el.id === id); console.log(getElById(config, 'qux')) console.log(getElById(config, 'abc')) console.log(getElById(config, 'bcd'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.