Skip to content

Instantly share code, notes, and snippets.

@lionelB
Last active August 29, 2015 13:55
Show Gist options
  • Save lionelB/8689549 to your computer and use it in GitHub Desktop.
Save lionelB/8689549 to your computer and use it in GitHub Desktop.
flatten object hierarchy. Rely on (underscore|lodash).js - Object's keys with the same name will be overwritten
_.reduce(o, function red(memo, val, key){
if(typeof val === 'object'){
_.reduce(val, red, memo)
} else {
memo[key] = val;
}
return memo;
}, Object.create(null));
@bloodyowl
Copy link

my take on this one (to prevent overwrites)

var hasOwn = {}.hasOwnProperty

function flatten(object, optionalArray){
  var key
    , item
    , array = optionalArray || []
  for(key in object) {
    if(!hasOwn.call(object, key)) continue
    item = object[key]
    if(item && typeof item == "object") {
      flatten(item, array)
      continue
    }
    array.push([key, item])
  }
  return array
}
flatten({foo:"bar", bar:{foo:"baz", bar:{foo:"foo"}}})
// -> [["foo","bar"],["foo","baz"],["foo","foo"]]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment