How to convert nested object into an array in javascript?

≯℡__Kan透↙ 提交于 2020-01-05 04:04:08

问题


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
    }
];

回答1:


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; }



回答2:


use _.values to get object values

var res = _.flatMap(array1, _.values)



回答3:


This solution uses spread syntax, and arrow functions (ES6), and Object.values() (ECMAScript 2017), so it won't work on old browsers without transpiling:

const 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 } }];

const result = [].concat(...array.map(Object.values));

console.log(result);

If all objects' keys are unique, you also use Object.assign() to combine all objects to a single one, then extract the values to an array with Object.values():

const 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 } }];

const result = Object.values(Object.assign({}, ...array));

console.log(result);



回答4:


answer=[];
for(elem of array){
var arr=[];
 for(obj of elem){
   arr.push(obj);
 }
answer.push(arr);
}
alert(answer);

Loop trough the main array, and replace each elem with an array.



来源:https://stackoverflow.com/questions/41427699/how-to-convert-nested-object-into-an-array-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!