Flatten json object


  • 0
    D

    Implement a method to flatten a json like input object. {x:1, y:1, z:{a:1,b:2}} flattens to {x:1, y:1, z.a:1, z.b: 2}


  • 1

    This is my JavaScript recursive solution, res holds the flattened result, we go through each property in the input obj, if it's an object, carry the current path and dig into it, otherwise, simply add it to the result.

    In JavaScript, if you worry about stack overflow when calling recursively, we can use setTimeout to avoid it.

    function flattenJSON(obj) {
      var res = {};
      helper(obj, res, "");
      return res;
    }
    
    function helper(obj, res, parent) {
      for (var prop in obj) {
        if (obj.hasOwnProperty(prop)) {
          var path = parent.length ? parent + "." + prop : prop;
          
          if (typeof obj[prop] === "object") {
            helper(obj[prop], res, path);
          } else {
            res[path] = obj[prop];
          }
        }
      }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.