【问题标题】:Object rest/spread only excising properties对象休息/传播仅切除属性
【发布时间】:2018-02-15 13:43:26
【问题描述】:

我想知道它是否可以通过 rest/spread 仅覆盖对象上的现有属性:

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

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

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

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

这可能吗?

提前致谢!

【问题讨论】:

  • 只需枚举xy的属性并签入xyz
  • 为什么x键的值是42
  • 我已经更新了,谢谢

标签: javascript typescript object


【解决方案1】:

Rest/spread 将始终将它在源对象中找到的内容填充到目标中,如果您不想使用循环/想要功能方法,请选择 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);

【讨论】:

    【解决方案2】:

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

     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);
    

    【讨论】:

      猜你喜欢
      • 2019-05-14
      • 2020-05-09
      • 2016-12-30
      • 1970-01-01
      • 2021-05-18
      • 2021-02-12
      • 2020-03-09
      • 2019-05-25
      • 2018-07-26
      相关资源
      最近更新 更多