Last active
April 13, 2020 17:42
-
-
Save anshuraj/186da185ae1fe299730e6333e41a0840 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Using recursion to flat object. | |
function magic(obj, name) { | |
let myObj = {}; | |
for (let key in obj) { | |
if (typeof obj[key] !== 'object') { | |
myObj[name + '_' + key] = obj[key]; | |
} else { | |
const magicValue = magic(obj[key], name + '_' + key); | |
// for (let i in magicValue) { | |
// myObj[name + '_' + i] = magicValue[i]; | |
// } | |
myObj = { | |
...myObj, | |
...magicValue | |
} | |
} | |
} | |
return myObj; | |
} | |
let user = { | |
name: { | |
firstName: "Jack", | |
lastName: "Reacher" | |
}, | |
age: 25, | |
address: { | |
present: { | |
houseNo: '110', | |
locality: 'West Road', | |
city: 'New York' | |
}, | |
permanent: { | |
houseNo: '7', | |
locality: 'South Side', | |
city: 'Riverdale' | |
} | |
}, | |
phoneNumber: 34500929 | |
}; | |
magic(user, 'user'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment