在 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 次浏览

开启您的 职业生涯

完成课程以获得认证

开始学习
广告
© . All rights reserved.