Update unflattenObject.md

This commit is contained in:
Angelos Chalaris
2020-09-22 22:37:05 +03:00
committed by GitHub
parent 351ce48f64
commit c86c2c8744

View File

@ -6,18 +6,25 @@ tags: object,advanced
Unflatten an object with the paths for keys.
- Use nested `Array.prototype.reduce()` to convert the flat path to a leaf node.
- Split each key with a dot delimiter (`.`) using `Array.prototype.split('.')`and use `Array.prototype.reduce()` to add or objects against the keys.
- If the current accumulator already contains value against a particular key, return its value as the next accumulator.
- Otherwise, add the appropriate key-value pair to the accumulator object and return value as the accumulator.
- Use `String.prototype.split('.')` to split each key with a dot delimiter and `Array.prototype.reduce()` to add objects against the keys.
- If the current accumulator already contains a value against a particular key, return its value as the next accumulator.
- Otherwise, add the appropriate key-value pair to the accumulator object and return the value as the accumulator.
```js
const unflattenObject = obj =>{
return Object.keys(obj).reduce((res , k)=>{
k.split('.').reduce(function(acc, e, i , keys) {
return acc[e] || (acc[e] = isNaN(Number(keys[i + 1])) ? (keys.length - 1 === i ? obj[k] : {}) : []);
}, res)
return res;
},{});
}
const unflattenObject = obj =>
Object.keys(obj).reduce((res, k) => {
k.split('.').reduce(
(acc, e, i, keys) =>
acc[e] ||
(acc[e] = isNaN(Number(keys[i + 1]))
? keys.length - 1 === i
? obj[k]
: {}
: []),
res
);
return res;
}, {});
```
```js