如何将一个对象的现有属性复制到另一个角度?

时间:2018-11-06 05:59:23

标签: javascript angular typescript

考虑以下代码:

const x={name:"a"};
const y={name:"b", fname:"c"};
const z = Object.assign(x,y); //output: z={name:"b", fname:"c"}
//expected: {name:"b"}

如何达到预期效果?

3 个答案:

答案 0 :(得分:1)

您可以使用for...in循环

const x={name:"a"};
const y={name:"b", fname:"c"};
const z = {};
for (let key in x) z[key] = y.hasOwnProperty(key) ? y[key] : x[key];
console.log(z);

答案 1 :(得分:0)

Object.prototype.customAssign = function(x,y){
   let item = {};
   Object.keys(x).forEach(function(a,b){ 
      destiKeys.indexOf(a)>=0? item[a] = y[a] : null;
   });
   return item;
};

const x={name:"a"};
const y={name:"b", fname:"c"};
const z = Object.customAssign(x,y); //output: z = {name:"b"} 

答案 2 :(得分:0)

使用spreadOperator https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html

z={...x,..y} //All properties of x + All properties of y
             //y properties replace the sames properties of x