Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Full path of a json object

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 whole path.

Sample Input:

{
  one: 1,
  two: {
    three: 3
  },
  four: {
    five: 5,
    six: {
      seven: 7
    },
    eight: 8
  },
  nine: 9
}

Output:

{
  one: 1,
  'two.three': 3,
  'four.five': 5,
  'four.six.seven': 7,
  'four.eight': 8,
  nine: 9
}
like image 804
Sayem Avatar asked Sep 17 '16 13:09

Sayem


2 Answers

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);
like image 165
Nina Scholz Avatar answered Oct 06 '22 11:10

Nina Scholz


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));
like image 21
knutesten Avatar answered Oct 06 '22 10:10

knutesten