Full path of a json object

前端 未结 9 702
忘了有多久
忘了有多久 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:53

    var obj = {
      one: 1,
      two: {
        three: 3
      },
      four: {
        five: 5,
        six: {
          seven: 7
        },
        eight: 8
      },
      nine: 9
    };
    
    function flatten(obj) {
      var flatObj = {}
    
      function makeFlat(obj, path) {
        var keys = Object.keys(obj);
        if (keys.length) {
          keys.forEach(function (key) {
            makeFlat(obj[key], (path ? path + "." : path) + key);
          })
        } else {
          flatObj[path] = obj;
        }
      }
      makeFlat(obj, "");
      return flatObj;
    }
    
    console.log(flatten(obj));

    0 讨论(0)
  • 2021-01-12 06:56

    You could use a recursive approch and collect the keys of the object. This proposal looks for arrays as well.

    function getFlatObject(object) {
        function iter(o, p) {
            if (o && typeof o === 'object') {
                Object.keys(o).forEach(function (k) {
                    iter(o[k], p.concat(k));
                });
                return;
            }
            path[p.join('.')] = o;
        }
    
        var path = {};
        iter(object, []);
        return path;
    }
    
    var obj = { one: 1, two: { three: 3 }, four: { five: 5, six: { seven: 7 }, eight: 8 }, nine: 9 },
        path = getFlatObject(obj);
    	
    console.log(path);

    0 讨论(0)
  • 2021-01-12 06:58

    You might simply do as follows;

    var obj = {one: 1, two: {three: 3}, four: {five: 5, six: {seven: 7}, eight: 8}, nine: 9},
    flatObj = (o,p="") => { return Object.keys(o)
                                         .map(k => o[k] === null           ||
                                                   typeof o[k] !== "object" ? {[p + (p ? ".":"") + k]:o[k]}
                                                                            : flatObj(o[k],p + (p ? ".":"") + k))
                                         .reduce((p,c) => Object.assign(p,c));
                          };
    console.log(flatObj(obj));

    0 讨论(0)
提交回复
热议问题