Convert the nested object to array JavaScript | Example code

  • by

Use a combined approach with iterating over the array and over the keys for Convert the nested object to array (Flat array) JavaScript.

Convert a nested object to array JavaScript

Simple example code where array have objects with two or more sub objects. Let’s get together all sub objects into an array of data.

<!DOCTYPE html>
<html>
<body>

  <script>
    var array =  [
    {
      "dfgasg24":{
        name:"a",
        id:1
      },
      "dfgare24":{
        name:"b",
        id:2
      }
    },
    {
      "wegasg24":{
        name:"ab",
        id:76
      },
      "yugasg24":{
        name:"bc",
        id:34
      },
      "yugasg26":{
        name:"dc",
        id:45
      }
    }
    ]
    
    result = array.reduce(function (r, o) {
      Object.keys(o).forEach(function (k) {
        r.push(o[k]);
      });
      return r;
    }, []);

    console.log(result);

  </script>

</body>
</html> 

Output:

Convert the nested object to array JavaScript

Achive this same result using recursion.

const input = {
  id: 1,
  name: "nameOne",
  parent: {
    id: 2,
    name: "nameTwo",
    parent: {
      id: 3,
      name: "nameThree",
      parent: null
    },
  },
};

function getResult(obj) {
  if (!obj) return;

  const { parent, ...rest } = obj;
  result.push({ ...rest });
  getResult(parent);
}

const result = [];
getResult(input);

console.log(result);

Output:

[
  {
    "id": 1,
    "name": "nameOne"
  },
  {
    "id": 2,
    "name": "nameTwo"
  },
  {
    "id": 3,
    "name": "nameThree"
  }
]

How to convert nested object into array of array?

Answer: Simple map the result of Object.values and For older user agents, you could use a polyfill.

The Object.values() method returns an array of a given object’s own enumerable property values, in the same order as that provided by a for…in loop.

<script>

    var array = [{ location: "MUGABALA  KOLAR ROAD", latitude: 13.108435679884, longitude: 77.890262391016 }, { location: "pune", latitude: 18.6202008, longitude: 73.7908073 }, { location: "RAJARAJESHWARI NAGAR BANGLORE", latitude: 12.901112992767, longitude: 77.5037757 }],

    result = array.map(Object.values);
    
    console.log(result);

</script>

Output:

0: Array(3) [ "MUGABALA  KOLAR ROAD", 13.108435679884, 77.890262391016 ]
​
1: Array(3) [ "pune", 18.6202008, 73.7908073 ]
​
2: Array(3) [ "RAJARAJESHWARI NAGAR BANGLORE", 12.901112992767, 77.5037757 ]

Do comment if you have any doubts or suggestions on this JS nested object 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

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.