Skip to content
Advertisement

How to flatten an object with nested objects in javascript

I have some attributes from a nested object that is inside the parent object but I would like to merge nested object with the parent object to be flatten.

Original object:

enrollment = {
  user: {
    id: 'string',
    name: 'string'
  },
  finished: 'boolean',
  path: 'string'
}

expected flatten object:

user: {
  id: 'string',
  name: 'string',
  finished: 'boolean',
  path: 'string'
}

Advertisement

Answer

You can recursively build object any number of nested objects. So, this function is not your case dependent:

var enrollment = {
user: {
    id: 'string',
    name: 'string'
},
finished: 'boolean',
path: 'boolean'
}

var enrollment2 = {
user: {
    id: 'string',
    name: 'string'
},
test: {
    test1: {
        test2: {
            val0:'val0',
            test4: { //3rd level nested object for example
                val1: 'val1',
                val2: 'val2'
            }
        }
    }
},
finished: 'boolean',
path: 'boolean'
}

const flat = (obj, out) => {
    Object.keys(obj).forEach(key => {
        if (typeof obj[key] == 'object') {
            out = flat(obj[key], out) //recursively call for nesteds
        } else {
            out[key] = obj[key] //direct assign for values
        }

    })
    return out
}

console.log(flat(enrollment, {}))
console.log(flat(enrollment2, {}))
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement