Flatten JavaScript Object with Recursion

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore a JavaScript function that flattens an object with the paths for keys. The function uses recursion and Object.keys() combined with Array.prototype.reduce() to convert every leaf node to a flattened path node. By the end of this lab, you will have a better understanding of how to manipulate JavaScript objects and flatten them for easier data processing.


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/cond_stmts("`Conditional Statements`") javascript/BasicConceptsGroup -.-> javascript/array_methods("`Array Methods`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") javascript/AdvancedConceptsGroup -.-> javascript/destr_assign("`Destructuring Assignment`") javascript/AdvancedConceptsGroup -.-> javascript/template_lit("`Template Literals`") subgraph Lab Skills javascript/variables -.-> lab-28312{{"`Flatten JavaScript Object with Recursion`"}} javascript/data_types -.-> lab-28312{{"`Flatten JavaScript Object with Recursion`"}} javascript/arith_ops -.-> lab-28312{{"`Flatten JavaScript Object with Recursion`"}} javascript/comp_ops -.-> lab-28312{{"`Flatten JavaScript Object with Recursion`"}} javascript/cond_stmts -.-> lab-28312{{"`Flatten JavaScript Object with Recursion`"}} javascript/array_methods -.-> lab-28312{{"`Flatten JavaScript Object with Recursion`"}} javascript/higher_funcs -.-> lab-28312{{"`Flatten JavaScript Object with Recursion`"}} javascript/destr_assign -.-> lab-28312{{"`Flatten JavaScript Object with Recursion`"}} javascript/template_lit -.-> lab-28312{{"`Flatten JavaScript Object with Recursion`"}} end

Flattening an Object

To flatten an object with paths for keys, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use recursion to flatten the object.
  3. Use Object.keys() combined with Array.prototype.reduce() to convert every leaf node to a flattened path node.
  4. If the value of a key is an object, call the function recursively with the appropriate prefix to create the path using Object.assign().
  5. Otherwise, add the appropriate prefixed key-value pair to the accumulator object.
  6. Omit the second argument, prefix, unless you want every key to have a prefix.

Here is an example implementation:

const flattenObject = (obj, prefix = "") =>
  Object.keys(obj).reduce((acc, k) => {
    const pre = prefix.length ? `${prefix}.` : "";
    if (
      typeof obj[k] === "object" &&
      obj[k] !== null &&
      Object.keys(obj[k]).length > 0
    ) {
      Object.assign(acc, flattenObject(obj[k], pre + k));
    } else {
      acc[pre + k] = obj[k];
    }
    return acc;
  }, {});

You can use the flattenObject function like this:

flattenObject({ a: { b: { c: 1 } }, d: 1 }); // { 'a.b.c': 1, d: 1 }

Summary

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

Other JavaScript Tutorials you may like