Let’s recap the flatted object we have created in the last article
const flattedObject ={
'user.name': 'Jeff',
'user.age': 24,
'user.hobbies': [ 'Piano', 'Software Development', 'Foods' ],
'user.address.country': 'Malaysia',
'user.address.state': 'Kuala Lumpur'
}
Unflatten Object
In this example, we will be utilizing the Array.prototype.reduce
methods to unflatten the object
|
|
Result
{
user: {
name: 'Jeff',
age: 24,
hobbies: [ 'Piano', 'Software Development', 'Foods' ],
address: {
country: 'Malaysia',
state: 'Kuala Lumpur' }
}
}
Explanation
- Firstly, we created an object for us to return later.
- Iterate the object by using for…in which allow us to acess all keys from the object
- However, the key of the object might flatted with nested object by full stop .. For instance,
'user.name'
should be equavalent to user:{name :{<value>
}} - As we can see from the
flattedObject
variable. The object keys are combined with the full stop .. So we can separate them by using split method. - As split method will return us an array. Now, we could iterate this array with
Array.prototype.reduce
method - We first assign the object variable =>
res
as it initial value. Then we can start to iterate the object keys and create the following conditions- assign the value to current iterated object key if current index is equal to the last index of the object keys
- Otherwise, create an empty object and continue iterate for the remaining keys