Categories
JavaScript Answers

How to Flatten a Nested JSON Object with JavaScript?

Spread the love

We can loop through each object property and check if a property is an object.

If it is, then we put the key in an object.

For instance, we can write:

const flatten = (obj, prefix = [], current = {}) => {
  if (typeof(obj) === 'object' && obj !== null) {
    for (const key of Object.keys(obj)) {
      flatten(obj[key], prefix.concat(key), current)
    }
  } else {
    current[prefix.join('.')] = obj
  }
  return current
}

console.log(flatten({
  a: [{
    b: ["c", "d"]
  }]
}));
console.log(flatten([1, [2, [3, 4], 5], 6]));

We create the flatten function that takes the obj , prefix , and current parameters.

prefix is the property name of the nested object.

current is the current value of the flattened object.

In the function body, we check if obj is an object and that obj isn’t null .

If they’re both true, then we know obj is an object.

Then we can loop through the keys obtained from Object.keys and call flatten inside the loop with the obj[key] , prefix , and current to traverse to the nested object.

Otherwise, obj isn’t an object and we can put the property as a property of current .

Now when we do run the 2 console log statements, we get:

{a.0.b.0: "c", a.0.b.1: "d"}

and:

{0: 1, 2: 6, 1.0: 2, 1.1.0: 3, 1.1.1: 4, 1.2: 5}

respectively.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *