在 JavaScript 中將物件陣列轉換成普通物件


假設我們有一個這樣的物件陣列 −

const arr = [{
   name: 'Dinesh Lamba',
   age: 23,
   occupation: 'Web Developer',
}, {
   address: 'Vasant Vihar',
   experience: 5,
   isEmployed: true
}];

我們需要編寫一個 JavaScript 函式,該函式採用這樣一個物件陣列。然後,該函式應準備一個物件,其中包含存在於陣列所有物件中的所有屬性。

因此,對於上述陣列,輸出應如下所示 −

const output = {
   name: 'Dinesh Lamba',
   age: 23,
   occupation: 'Web Developer',
   address: 'Vasant Vihar',
   experience: 5,
   isEmployed: true
};

示例

以下是程式碼 −

const arr = [{
   name: 'Dinesh Lamba',
   age: 23,
   occupation: 'Web Developer',
}, {
   address: 'Vasant Vihar',
   experience: 5,
   isEmployed: true
}];
const mergeObjects = (arr = []) => {
   const res = {};
   arr.forEach(obj => {
      for(key in obj){
         res[key] = obj[key];
      };
   });
   return res;
};
console.log(mergeObjects(arr));

輸出

以下是控制檯輸出 −

{
   name: 'Dinesh Lamba',
   age: 23,
   occupation: 'Web Developer',
   address: 'Vasant Vihar',
   experience: 5,
   isEmployed: true
}

更新於: 18 年 1 月 2021 日

534 次瀏覽

開啟您的 職業生涯

完成課程以獲得認證

開始學習
廣告