Traverse all the Nodes of a JSON Object Tree with JavaScript

前端 未结 16 1394
猫巷女王i
猫巷女王i 2020-11-22 06:26

I\'d like to traverse a JSON object tree, but cannot find any library for that. It doesn\'t seem difficult but it feels like reinventing the wheel.

In XML there are

16条回答
  •  不思量自难忘°
    2020-11-22 07:19

    We use object-scan for all our data processing needs now. It's very powerful once you wrap your head around it. Here is how you could do basic traversal

    const objectScan = require('object-scan');
    
    const obj = {
      foo: 'bar',
      arr: [1, 2, 3],
      subo: {
        foo2: 'bar2'
      }
    };
    
    objectScan(['**'], {
      filterFn: ({ key, value }) => {
        console.log(key, value);
      }
    })(obj);
    /* =>
    [ 'subo', 'foo2' ] 'bar2'
    [ 'subo' ] { foo2: 'bar2' }
    [ 'arr', 2 ] 3
    [ 'arr', 1 ] 2
    [ 'arr', 0 ] 1
    [ 'arr' ] [ 1, 2, 3 ]
    [ 'foo' ] 'bar'
    */
    

提交回复
热议问题