Skip to content

Instantly share code, notes, and snippets.

@anshuraj
Last active April 13, 2020 17:42
Show Gist options
  • Save anshuraj/186da185ae1fe299730e6333e41a0840 to your computer and use it in GitHub Desktop.
Save anshuraj/186da185ae1fe299730e6333e41a0840 to your computer and use it in GitHub Desktop.
// 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