Last active
December 4, 2022 15:19
-
-
Save mulrooneydesign/8dbacc72c0bcdf86ec59ae67ff722d27 to your computer and use it in GitHub Desktop.
Flatten a nested object in javascript
This file contains hidden or 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
| // deeply nested object about a person that we are going to flatten | |
| const person = { | |
| name: 'John', | |
| age: 30, | |
| address: { | |
| street: '123 Main St', | |
| city: 'New York', | |
| state: 'NY', | |
| zip: 10001, | |
| country: { | |
| name: 'United States', | |
| code: 'US', | |
| }, | |
| }, | |
| } | |
| // lowercase first letter of a string | |
| const lowerFirst = (str) => { | |
| return str.charAt(0).toLowerCase() + str.slice(1) | |
| } | |
| // upperCase first letter of a string | |
| const upperFirst = (str) => { | |
| return str.charAt(0).toUpperCase() + str.slice(1) | |
| } | |
| // function that creates a flat object from a nested object | |
| const flattenObject = (obj) => { | |
| // create a new object | |
| const flattened = {} | |
| // get the keys of the object | |
| const keys = Object.keys(obj) | |
| // iterate through the keys | |
| keys.forEach((key) => { | |
| // if the value of the key is an object | |
| if (typeof obj[key] === 'object') { | |
| // get the keys of the nested object | |
| const flatObject = flattenObject(obj[key]) | |
| // iterate through the keys of the nested object | |
| Object.keys(flatObject).forEach((k) => { | |
| // add the key and value to the new object | |
| flattened[`${lowerFirst(key)}${upperFirst(k)}`] = flatObject[k] | |
| }) | |
| } | |
| // if the value of the key is not an object | |
| else { | |
| // add the key and value to the new object | |
| flattened[key] = obj[key] | |
| } | |
| }) | |
| // return the new object | |
| return flattened | |
| } | |
| console.log(flattenObject(person)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment