JavaScript: Flatten a Nested JSON Object

In this tutorial, we will use an example to show you how to flatten a nested JSON object.

JavaScript - Flatten a Nested JSON Object - A Step Guide

1.We should use flat library

npm install flat

2.Import flat library

const flatten = require('flat').flatten;

3.Prepare a nested json object

const obj = {
   name: "John",
   age: 10,
   address: {
       street: "Street 1",
       postalCode: "7557-40"
   },
   favouriteCountries: ["Portugal", "Spain"],
   nestedObject: { x: { y: { z: {w: "property" } } } }
}

4.Start to flatten json object

console.log(flatten(obj));

Run this code, you will see a flatten json.

JavaScript: Flatten a Nested JSON Object