JavaScript recursive search in JSON object

后端 未结 6 483
野趣味
野趣味 2020-11-30 04:21

I am trying to return a specific node in a JSON object structure which looks like this

{
    \"id\":\"0\",
    \"children\":[
        {
            \"id\":\"         


        
6条回答
  •  春和景丽
    2020-11-30 04:44

    I would try not to reinvent the wheel. We use object-scan for all our data processing needs. It's conceptually very simple, but allows for a lot of cool stuff. Here is how you would solve your specific question

    const objectScan = require('object-scan');
    
    const findNode = (id, input) => objectScan(['**'], {
      abort: true,
      rtn: 'value',
      filterFn: ({ value }) => value.id === id
    })(input);
    
    const data = {
      id: '0',
      children: [{
        id: '1',
        children: [
          { id: '3', children: [] },
          { id: '4', children: [] }
        ]
      }, {
        id: '2',
        children: [
          { id: '5', children: [] },
          { id: '6', children: [] }
        ]
      }]
    };
    
    console.log(findNode('6', data));
    // => { id: '6', children: [] }
    

提交回复
热议问题