假设我们有一个这样的对象数组-
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 }