在 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
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP