对象休息/仅传播切除属性

时间:2018-02-15 13:43:26

标签: javascript typescript object

我想知道是否可以使用rest / spread来覆盖对象的现有属性:

let xy = {
 x: 1,
 y: 2,
} 

let xyz = {
 x: 41,
 y: 23,
 z: 1
} 

现在我有两个对象,我希望覆盖xy上的现有属性,而不从z获取xyz属性,因此我的输出如下:

xy = {
 x: 41,
 y: 23,
} 

这可能吗?

提前致谢!

2 个答案:

答案 0 :(得分:2)

休息/传播将始终填充到它在源对象中找到的目标,如果您不想使用循环/想要一种功能方法,请转到reduce,例如

const xyNew = Object.keys(xyz).reduce((res, key) =>
    // if the key is contained in the accumulator, rewrite it with xyz value, else just return the accumulator (res ~ "result")
    res[key] ? { ...res, [key]: xyz[key] } : res
, xy);

答案 1 :(得分:1)

这是一个简单的实现: - )

 let xy = {
 x: 1,
 y: 2,
} 

let xyz = {
 x: 41,
 y: 23,
 z: 1
} 
function compute(){
    let key = Object.keys(xy);
    for(let i=0;i<key.length;i++){
        if(key[i] in xyz) xy[key[i]] = xyz[key[i]];
    }
}
compute();
console.log(xy);
相关问题