如何使用 JavaScript 將物件物件轉換為物件陣列物件?


想要將物件物件轉換為物件陣列物件,使用 Object.fromEntries() 與 map() 的概念即可實現。

示例

const studentDetails = {
   'details1': {Name: "John", CountryName: "US"},
   'details2': {Name: "David", CountryName: "AUS"},
   'details3': {Name: "Bob", CountryName: "UK"},
};
console.log(
   Object.fromEntries(Object.entries(studentDetails).map(([key,
   value]) => [key, [value]]))
);

想要執行以上程式,你需要使用以下命令 −

node fileName.js.

這裡,我的檔名是 demo45.js。

輸出

這會產生以下輸出 −

PS C:\Users\Amit\JavaScript-code> node demo45.js
{
   details1: [ { Name: 'John', CountryName: 'US' } ],
   details2: [ { Name: 'David', CountryName: 'AUS' } ],
   details3: [ { Name: 'Bob', CountryName: 'UK' } ]
}

更新於: 02-Sep-2020

697 人瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.