簡體   English   中英

如何在JavaScript中將嵌套對象轉換為數組?

[英]How to convert nested object into an array in javascript?

我有一個包含多個對象的數組。 在此數組中,每個對象都有兩個或多個子對象。 我想將所有子對象聚集到一個數據數組中。 如何使用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
    }
];

您可以使用組合方法來遍歷數組和鍵,以構建平面數組。

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

使用_.values獲取對象值

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

此解決方案使用傳播語法箭頭功能 (ES6)和Object.values() (ECMAScript 2017),因此,如果不進行編譯,它將無法在舊的瀏覽器上運行:

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

如果所有對象的鍵都是唯一的,則還可以使用Object.assign()將所有對象組合為一個對象,然后使用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); 

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

循環遍歷主數組,然后將每個elem替換為一個數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM