I need to deep reverse the order of all keys in a JavaScript object.
For example:
{
a: 'val1',
b: 'val2',
c: {
ca: 'val3',
cb: 'val4'
}
}
Must become:
{
c: {
cb: 'val4',
ca: 'val3'
},
b: 'val2',
a: 'val1'
}
I have tried writing a recursive function, but I cannot figure out how to fix it:
function reverseKeys (obj, newObj = {}) {
Object.keys(obj).reverse().forEach(key => {
if(typeof obj[key] === 'object') {
newObj = reverseKeys(obj[key], {})
}
newObj[key] = obj[key]
})
return newObj
}
Solution inspired by @Unmitigated's input
function reverseKeys (obj) {
return Object.fromEntries(
Object.entries(obj)
.reverse()
.map(
([k, v]) => {
if (v.constructor === Object && v.constructor !== Array && v !== null) {
return [k, reverseKeys(v)]
} else if (v.constructor === Array && v !== null) {
const a = []
v.forEach(elem => {
if ((elem.constructor === Object || elem.constructor === Array) && elem !== null) {
a.push(reverseKeys(elem))
} else {
a.push(elem)
}
})
return [k, a]
} else {
return [k, v]
}
}
)
)
}