Full path of a json object

前端 未结 9 805
忘了有多久
忘了有多久 2021-01-12 06:02

I\'m trying to flatten an object where the keys will be the full path to the leaf node. I can recursively identify which are the leaf nodes but stuck trying to construct the

9条回答
  •  忘掉有多难
    2021-01-12 06:51

    Here is an interative solution using object-scan.

    object-scan is a data processing tool, so the main advantage here is that it would be easy to do further processing or processing while extracting the desired information

    // const objectScan = require('object-scan');
    
    const myData = { one: 1, two: { three: 3 }, four: { five: 5, six: { seven: 7 }, eight: 8 }, nine: 9 };
    
    const flatten = (data) => {
      const entries = objectScan(['**'], {
        rtn: 'entry',
        joined: true,
        filterFn: ({ isLeaf }) => isLeaf
      })(data);
      // could use Object.fromEntries(entries.reverse()) instead
      return entries.reduceRight((p, [k, v]) => {
        p[k] = v;
        return p;
      }, {});
    };
    
    console.log(flatten(myData));
    // => { one: 1, 'two.three': 3, 'four.five': 5, 'four.six.seven': 7, 'four.eight': 8, nine: 9 }
    .as-console-wrapper {max-height: 100% !important; top: 0}

    Disclaimer: I'm the author of object-scan

提交回复
热议问题