使用散布和解构运算符修改不可变对象的最短方法是什么 [英] What is the shortest way to modify immutable objects using spread and destructuring operators

查看:45
本文介绍了使用散布和解构运算符修改不可变对象的最短方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个纯函数,以修改我的不可变状态对象.作为参数给出的原始状态必须保持不变.这在使用 Redux 之类的框架并使其与 Babel 与对象散布算子一起工作已经成为可能.

I'm looking for a pure function, to modify my immutable state object. The original state given as parameter must stay untouched. This is especially useful when working with frameworks like Redux and makes working with immutable object in javascript much easier. Especially since working with the object spread operator using Babel is already possible.

我发现没有比首先复制对象以及分配/删除我想要的属性更好的东西了:

I did not found anything better than first copy the object, and than assign/delete the property I want like this:

function updateState(state, item) {
  newState = {...state};
  newState[item.id] = item;
  return newState;
}

function deleteProperty(state, id) {
    var newState = {...state};
    delete newState[id];
    return newState;
}

我觉得它可能会更短

推荐答案

对状态的操作,其中状态被认为是不可变的.

Actions on state, where state is considered immutable.

添加或更新属性值:

// ES6:
function updateState(state, item) {
    return Object.assign({}, state, {[item.id]: item});
}

// With Object Spread:
function updateState(state, item) {
  return {
     ...state,
     [item.id]: item
  };
}

删除媒体资源

// ES6:
function deleteProperty(state, id) {
    var newState = Object.assign({}, state);
    delete newState[id];
    return newState; 
}

// With Object Spread:
function deleteProperty(state, id) {
    let  {[id]: deleted, ...newState} = state;
    return newState;
}

// Or even shorter as helper function:
function deleteProperty({[id]: deleted, ...newState}, id) {
    return newState;
}

// Or inline:
function deleteProperty(state, id) {
    return (({[id]: deleted, ...newState}) => newState)(state);
}

这篇关于使用散布和解构运算符修改不可变对象的最短方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆