Unflatten Nested JavaScript Objects

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to unflatten an object with paths for keys in JavaScript. We will use nested Array.prototype.reduce() and String.prototype.split() methods to split each key with a dot delimiter and add objects against the keys. By the end of this lab, you will have a solid understanding of how to efficiently convert a flat object to a nested one.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/array_methods("`Array Methods`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") javascript/AdvancedConceptsGroup -.-> javascript/destr_assign("`Destructuring Assignment`") subgraph Lab Skills javascript/variables -.-> lab-28678{{"`Unflatten Nested JavaScript Objects`"}} javascript/data_types -.-> lab-28678{{"`Unflatten Nested JavaScript Objects`"}} javascript/arith_ops -.-> lab-28678{{"`Unflatten Nested JavaScript Objects`"}} javascript/comp_ops -.-> lab-28678{{"`Unflatten Nested JavaScript Objects`"}} javascript/array_methods -.-> lab-28678{{"`Unflatten Nested JavaScript Objects`"}} javascript/higher_funcs -.-> lab-28678{{"`Unflatten Nested JavaScript Objects`"}} javascript/destr_assign -.-> lab-28678{{"`Unflatten Nested JavaScript Objects`"}} end

How to Unflatten an Object in JavaScript

To unflatten an object with paths for keys in JavaScript, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.

  2. Use nested Array.prototype.reduce() to convert the flat path to a leaf node.

  3. Use String.prototype.split() to split each key with a dot delimiter and Array.prototype.reduce() to add objects against the keys.

  4. If the current accumulator already contains a value against a particular key, return its value as the next accumulator.

  5. Otherwise, add the appropriate key-value pair to the accumulator object and return the value as the accumulator.

Here's the code for the unflattenObject function:

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;
  }, {});

You can use the unflattenObject function to unflatten an object in JavaScript:

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 }

Summary

Congratulations! You have completed the Unflatten Object lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like