How to traverse all the nodes of a JSON object tree with JavaScript?

Sometimes, we want to traverse all the nodes of a JSON object tree with JavaScript.

In this article, we’ll look at how to traverse all the nodes of a JSON object tree with JavaScript.

How to traverse all the nodes of a JSON object tree with JavaScript?

To traverse all the nodes of a JSON object tree with JavaScript, we can use the Object.entries method.

For instance, we write

const traverse = (jsonObj) => {
  if (jsonObj !== null && typeof jsonObj == "object") {
    Object.entries(jsonObj).forEach(([key, value]) => {
      traverse(value);
    });
  } else {
    console.log(jsonObj);
  }
};

to create the traverse function.

In it, we loop through the key-value pairs with the Object.entries method.

If jsonObj is an object, then we call traverse with its value in the forEach callback to traverse the level below the current level.

Otherwise, we log the jsonObj value.

Conclusion

To traverse all the nodes of a JSON object tree with JavaScript, we can use the Object.entries method.