【问题标题】:How to update hashmap field by dynamic key using Object.assign and avoid mutations?如何使用 Object.assign 通过动态键更新 hashmap 字段并避免突变?
【发布时间】:2017-04-09 23:20:16
【问题描述】:

我如何定义updater 以在newState.c.x === 8 中为真并避免state 中的任何突变?

var state = {
    a: {x: 1, y: 1},
    b: {x: 2, y: 2},
    c: {x: 3, y: 3},
    d: {x: 4, y: 4},
};

var key = 'c';
var x = 8;

var updater = {
    //Having state, key and x here....

}

var newState = Object.assign({}, state, updater);
if(newState.c.x === 8) {
  wooHoo();

}

提前致谢!

【问题讨论】:

    标签: javascript hashmap


    【解决方案1】:

    你可以使用一些 ES6 解构和Object.assign()

    var state = {
        a: {x: 1, y: 1},
        b: {x: 2, y: 2},
        c: {x: 3, y: 3},
        d: {x: 4, y: 4},
    };
    
    var key = 'c';
    var x = 8;
    
    var updater = {
      [key]: Object.assign({}, state[key], {x})
    }
    
    var newState = Object.assign({}, state, updater);
    if(newState.c.x === 8) {
      alert('True')
    }

    【讨论】:

      猜你喜欢
      • 2017-07-09
      • 1970-01-01
      • 2016-11-06
      • 2021-06-06
      • 2012-02-21
      • 1970-01-01
      • 2014-12-22
      • 1970-01-01
      • 2018-01-08
      相关资源
      最近更新 更多