JavaScript: Unflatten an object with the paths for keys

JavaScript fundamental (ES6 Syntax): Exercise-112 with Solution

Write a JavaScript program to unflatten an object with the paths for keys.

  • Use nested Array.prototype.reduce() to convert the flat path to a leaf node.
  • 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.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2 
const unflattenObject = obj =>
  Object.keys(obj).reduce((acc, k) => {
    if (k.indexOf('.') !== -1) {
      const keys = k.split('.');
          '{' +
            keys.map((v, i) => (i !== keys.length - 1 ? `"${v}":{` : `"${v}":`)).join('') +
            obj[k] +
    } else acc[k] = obj[k];
    return acc;
  }, {});
console.log(unflattenObject({ 'a.b.c': 1, d: 1 }));

Sample Output:



flowchart: Unflatten an object with the paths for keys

Live Demo:

See the Pen javascript-basic-exercise-112-1 by w3resource (@w3resource) on CodePen.

Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to build an array, using an iterator function and an initial seed value.
Next: Write a JavaScript program to unescape escaped HTML characters.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.