Categories
interview

Use DFS to flatten Javascript Objects

This is straight forward implementation of the DFS (Depth First Search) traversal algorithm using recursion.

 var obj = {
  baz: {
    foo: {
      bar: "5"
    },
    hell: {
      sin: "0"
    }
  },
  a: {
    b: "1"
  }
};

var hash = {};
var str = '';

var dfs = function(obj, str) {
  for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
      if (typeof obj[key] === 'string')
        hash[str + key] = obj[key];
      else {
        dfs(obj[key], str + key + '.');
      }
    }
  }
};
dfs(obj, str);
console.log(hash);
var obj = {
  baz: {
    foo: {
      bar: "5"
    },
    hell: {
      sin: "0"
    }
  },
  a: {
    b: "1"
  }
};
var tracker = [];
var hashMap = {};
var hashKey = '';

function dfs(obj, tracker) {
  for (var key in obj) {
    if (obj.hasOwnProperty(key)) {

      if (typeof obj[key] == "string") {
        tracker.push(key);
        hashKey = appendArray(tracker);
        hashMap[hashKey] = obj[key];
        tracker.pop();
      } else {
        tracker.push(key);
        dfs(obj[key], tracker);
        tracker.pop();
      }
    }
  }
}
dfs(obj, tracker);
console.log(hashMap);

function appendArray(arr) {
  var ret = '';
  for (var i = 0; i < arr.length; i++) {
    ret = ret + '.' + arr[i];
  }
  return ret.substring(1, ret.length);
}

Output

Object {baz.foo.bar: "5", baz.another.bar: "0", a.b: "1"}

Demo