Skip to content

Instantly share code, notes, and snippets.

@ivan-kleshnin
Last active October 9, 2017 14:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivan-kleshnin/301a7e96be6c8725567f6832a49042df to your computer and use it in GitHub Desktop.
Save ivan-kleshnin/301a7e96be6c8725567f6832a49042df to your computer and use it in GitHub Desktop.
flattenObject

My code from: https://gist.github.com/penguinboy/762197

let isPlainObj = (o) => Object.prototype.toString.call(o) == "[object Object]"
// this ^ is enough. If you check prototypes – you're doing it wrong. If somethings pretends to be plain – we have to accept that
// e.g. this: https://github.com/jonschlinkert/is-plain-object is an entirely WRONG approach 

let flattenObj = (obj, keys=[]) => {
  return Object.keys(obj).reduce((acc, key) => {
    return Object.assign(acc, isPlainObj(obj[key])
      ? flattenObj(obj[key], keys.concat(key))
      : {[keys.concat(key).join(".")]: obj[key]}
    )
  }, {})
}
console.log(flattenObj({}) // {}
console.log(flattenObj({foo: "foo"}) // {foo: "foo"}
console.log(flattenObj({
  users: {
    set: "whatnot",
  },
  projects: {
    set: "whatnot",
  },
  dates: {
    d1: new Date(),
    d2: new Date(),
  },
  array: [{foo: "foo"}, {bar: "bar"}]
}))

{ 'users.set': 'whatnot',
  'projects.set': 'whatnot',
  'dates.d1': <dateobj1>,
  'dates.d2': <dateobj2>,
  array: [ { foo: 'foo' }, { bar: 'bar' } ] }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment