Skip to content

Convert nested JSON object to array JavaScript | Example code

  • by

Use the Object values method to convert nested JSON objects to arrays in JavaScript. This method returns an array of a given object’s own enumerable property values.

Object.values(data)

Convert nested JSON object to array JavaScript

Simple HTML example code.

<!DOCTYPE html>
<html>
<body>

  <script>
    var data = {
      code: 42,
      items: {
        item_1: {
          id: 1,
          name: 'foo'
        },
        item_2: {
          id: 2,
          name: 'bar'
        },
        item_3: {
          id: 2,
          name: 'bar'
        }
      }
    };

    const items = Object.values(data.items);
    console.log(items);
  </script>

</body>
</html> 

Output:

Convert nested JSON object to array JavaScript

Or you can use a recursive function that traverses the object and pushes its values into an array.

function flattenObject(obj) {
  const result = [];
  
  for (const key in obj) {
    const value = obj[key];
    
    if (typeof value === 'object' && value !== null) {
      result.push(...flattenObject(value));
    } else {
      result.push(value);
    }
  }
  
  return result;
}

This function takes an object as input and returns an array containing all the values in the object. If a value is itself an object, the function recursively calls itself to extract its values.

const nestedObject = {
  a: 1,
  b: {
    c: 2,
    d: {
      e: 3,
      f: 4
    }
  }
};

const flattenedArray = flattenObject(nestedObject);
console.log(flattenedArray); // [1, 2, 3, 4]

Do comment if you have any doubts or suggestions on this JS JSON topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading