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' ] ] }

更新於: 24-Nov-2020

353 次瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始學習
廣告
© . All rights reserved.