我们有一个这样的物体-
const obj1 = { name: " ", email: " " };
和另一个像这样-
const obj2 = { name: ['x'], email: ['y']};
我们需要编写一个接受两个这样的对象的JavaScript函数。并希望输出是这样的联合-
const output = { name: {" ", [x]}, email: {" ", [y]} };
为此的代码将是-
const obj1 = { name: " ", email: " " }; const obj2 = { name: ['x'], email: ['y']}; const objectUnion = (obj1 = {}, obj2 = {}) => { const obj3 = { name:[], email:[] }; for(let i in obj1) { obj3[i].push(obj1[i]); } for(let i in obj2) { obj3[i].push(obj2[i]); } return obj3; }; console.log(objectUnion(obj1, obj2));
输出结果
控制台中的输出将是-
{ name: [ ' ', [ 'x' ] ], email: [ ' ', [ 'y' ] ] }