Search code examples
javascriptjqueryarrayslodash

How to convert nested object into an array in javascript?


I have an array with multiple objects. In this array each objects having two or more sub objects. I want to get together all sub objects into an array of data. How to do with javascript?

var array1 = [
  {
    "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
    }
  }
]

The output which i want to be like this,

var result = [
    {
        name:"a",
        id:1
    },
    {
        name:"b",
        id:2
    },
    {
        name:"ab",
        id:76
    },
    {
        name:"bc",
        id:34
    },
    {
        name:"dc",
        id:45
    }
];

Solution

  • You could use a combined approach with iterating over the array and over the keys for building a flat array.

    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);
    .as-console-wrapper { max-height: 100% !important; top: 0; }