如何在JavaScript中将嵌套对象转换为数组? [英] How to convert nested object into an array in javascript?

查看:78
本文介绍了如何在JavaScript中将嵌套对象转换为数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多个对象的数组.在此数组中,每个对象都有两个或多个子对象.我想将所有子对象聚集到一个数据数组中.如何使用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
    }
  }
]

我想要的输出,

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

推荐答案

您可以使用组合方法在数组和键上进行迭代以构建平面数组.

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

这篇关于如何在JavaScript中将嵌套对象转换为数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆