fix issue #1175 and cater more scenarios
This commit is contained in:
@ -5,29 +5,27 @@ tags: object,advanced
|
|||||||
|
|
||||||
Unflatten an object with the paths for keys.
|
Unflatten an object with the paths for keys.
|
||||||
|
|
||||||
- Use `Object.keys(obj)` combined with `Array.prototype.reduce()` to convert flattened path node to a leaf node.
|
- Iterate over the object keys using `Object.keys(obj)` and `Array.prototype.forEach()`.
|
||||||
- If the value of a key contains a dot delimiter (`.`), use `Array.prototype.split('.')`, string transformations and `JSON.parse()` to create an object, then `Object.assign()` to create the leaf node.
|
- Split each key with a dot delimiter (`.`) using `Array.prototype.split('.')`and use `Array.prototype.reduce()` to convert flattened paths to leaf node.
|
||||||
- Otherwise, add the appropriate key-value pair to the accumulator object.
|
- 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.
|
||||||
|
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const unflattenObject = obj =>
|
const unflattenObject = obj =>{
|
||||||
Object.keys(obj).reduce((acc, k) => {
|
var result = {}
|
||||||
if (k.indexOf('.') !== -1) {
|
Object.keys(obj).forEach((k)=>{
|
||||||
const keys = k.split('.');
|
var keys = k.split('.')
|
||||||
Object.assign(
|
keys.reduce(function(acc, e, i) {
|
||||||
acc,
|
return acc[e] || (acc[e] = isNaN(Number(keys[i + 1])) ? (keys.length - 1 === i ? obj[k] : {}) : [])
|
||||||
JSON.parse(
|
}, result)
|
||||||
'{' +
|
})
|
||||||
keys.map((v, i) => (i !== keys.length - 1 ? `"${v}":{` : `"${v}":`)).join('') +
|
return result
|
||||||
obj[k] +
|
}
|
||||||
'}'.repeat(keys.length)
|
|
||||||
)
|
|
||||||
);
|
|
||||||
} else acc[k] = obj[k];
|
|
||||||
return acc;
|
|
||||||
}, {});
|
|
||||||
```
|
```
|
||||||
|
|
||||||
```js
|
```js
|
||||||
unflattenObject({ 'a.b.c': 1, d: 1 }); // { a: { b: { c: 1 } }, d: 1 }
|
unflattenObject({ 'a.b.c': 1, d: 1 }); // { a: { b: { c: 1 } }, d: 1 }
|
||||||
|
unflattenObject({ 'a.b': 1, 'a.c': 2, d: 3 }); // { a: { b: 1, c: 2 }, d: 3 }
|
||||||
|
unflattenObject({ 'a.b.0': 8, d: 3 }) //{ a: { b: [ 8 ] }, d: 3 }
|
||||||
```
|
```
|
||||||
|
|||||||
Reference in New Issue
Block a user