简体   繁体   中英

How to search and filter for nested property using Lodash?

I have an object shaped like this:

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,
          },
        ]
      },
    ],
  },
]

I need to access the object where the id property is qux by using some sort of " .deep " (recursive?) filter on the config array. Or some kind of " .flatten ", then " .filter " combo pattern.

How can I do this using Lodash?

You can do this with plain js with recursion and some method that will loop the array and exit on first match like 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)

Here is a vanilla ES6 solution without lodash or any other package. Simply flatten your original structure (I used a simple recursive function that takes advantage of Array.prototype.reduce - but there are other ways to flatten) then use Array.prototype.find to get your desired element.

For example (I nested the array deeper with some phony data, just to show that the solution should work no matter how many levels deep the children continue on for:

 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'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM