flattening the nested object in javascript
You should be able to do it fairly simply with recursion. The way it works, is you just recursively call a parser on object children that prepend the correct key along the way down. For example (not tested very hard though):
const source = { a: 1, b: { c: true, d: { e: 'foo' } }, f: false, g: ['red', 'green', 'blue'], h: [{ i: 2, j: 3 }]}const flatten = (obj, prefix = '', res = {}) => Object.entries(obj).reduce((r, [key, val]) => { const k = `${prefix}${key}` if(typeof val === 'object'){ flatten(val, `${k}.`, r) } else { res[k] = val } return r }, res) console.log(flatten(source))
I am very late to the party but it can be easily achieved with a module like Flatify-obj.
Usage:
const flattenObject = require('flatify-obj'); flattenObject({foo: {bar: {unicorn: '🦄'}}}) //=> { 'foo.bar.unicorn': '🦄' } flattenObject({foo: {unicorn: '🦄'}, bar: 'unicorn'}, {onlyLeaves: true}); //=> {unicorn: '🦄', bar: 'unicorn'}
one more simple example with Object.keys
const apple = { foo: { boo : { doo : 1 } } }let newObj = {}const format = (obj,str) => { Object.keys(obj).forEach((item)=>{ if(typeof obj[item] ==='object'){ const s = !!str? str+'.'+item:item format(obj[item],s) } else { const m = !!str?`${str}.`:'' newObj[m+item]= obj[item] } })}format(apple,'')console.log(newObj)