Below will be the object to be used and tested in both flatten and unflatten algorithm.
const object = {
user: {
name: "Jeff",
age: 24,
hobbies: ["Piano", "Software Development", "Foods"],
address: {
country: "Malaysia",
state: "Kuala Lumpur"
},
},
}Flatten Object
In this example, we are flattening the object by using recursive method
|
|
Result
{
'user.name': 'Jeff',
'user.age': 24,
'user.hobbies': [ 'Piano', 'Software Development', 'Foods' ],
'user.address.country': 'Malaysia',
'user.address.state': 'Kuala Lumpur'
}Explanation
- Create a function which takes in 3 arguments. (1 mandatory and 2 optional)
- Iterate the object by using for…in which allow us to acess all keys from the object
- As we are now trying to flatten the object keys, so it needed to combine with it’s previous key. If there is no previous key “only 1 layer / not nested object “ we will then use the current key as the flatten object key
- Check if the current value is an object by using the methods
typeof(), this case we added another condition!Array.isArray()is becausetypeof(Array)will still returning true but we only wanted to check object type.- If the value is an object type, we can then called the function recursively
flattenObj(obj[key], propName, res)by assigning the argument of- curreny value object
obj[key] - combined key name with previous key
- response object
- curreny value object
- else it will be now at the endpoint / last key of the nested object. And we can assign the actual value to it
res[propName] = obj[key]
- If the value is an object type, we can then called the function recursively