JavaScript 两个对象的联合
我们有一个这样的对象 −
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' ] ] }
广告