使用扩展符号深入复制ES6 [英] Deep copy in ES6 using the spread sign
问题描述
我正在尝试为我的Redux项目创建一个深层拷贝映射方法,该方法将使用对象而不是数组。我读到在Redux中,每个州不应该改变以前状态的任何东西。
I am trying to create a deep copy map method for my Redux project that will work with objects rather than arrays. I read that in Redux each state should not change anything in the previous states.
export const mapCopy = (object, callback) => {
return Object.keys(object).reduce(function (output, key) {
output[key] = callback.call(this, {...object[key]});
return output;
}, {});
}
它的作品:
return mapCopy(state, e => {
if (e.id === action.id) {
e.title = 'new item';
}
return e;
})
但是它不会深入复制内部项目,所以我需要调整它:
However it does not deep copy inner items so I need to tweak it to:
export const mapCopy = (object, callback) => {
return Object.keys(object).reduce(function (output, key) {
let newObject = {...object[key]};
newObject.style = {...newObject.style};
newObject.data = {...newObject.data};
output[key] = callback.call(this, newObject);
return output;
}, {});
}
它不太优雅,因为它需要知道哪些对象被传递。
ES6中有没有办法使用扩展符来深入复制对象?
This is less elegant as it requires to know which objects are passed. Is there a way in ES6 to use the spread sign to deep copy an object?
推荐答案
没有这样的功能内置ES6。我想你有几个选择取决于你想做什么。
No such functionality is built-in to ES6. I think you have a couple of options depending on what you want to do.
如果你真的想深入复制:
If you really want to deep copy:
- 使用库。例如,lodash具有
cloneDeep
方法。 - 实现您自己的克隆功能。
但是,如果您愿意换几件事情,可以节省一些工作。我假设你控制所有的调用站点到你的函数。
However, I think, if you're willing to change a couple things, you can save yourself some work. I'm assuming you control all call sites to your function.
-
指定所有回调传递给
mapCopy
必须返回新对象,而不是使现有的对象变异。例如:
Specify that all callbacks passed to
mapCopy
must return new objects instead of mutating the existing object. For example:
mapCopy(state, e => {
if (e.id === action.id) {
return Object.assign({}, e, {
title: 'new item'
});
} else {
return e;
}
});
这使用 Object.assign
来创建一个新对象,设置属性的 e
,然后在该对象上设置一个新的标题。这意味着你不会突变现有的对象,只有在必要时创建新的对象。
This makes use of Object.assign
to create a new object, sets properties of e
on that new object, then sets a new title on that new object. This means you never mutate existing objects and only create new ones when necessary.
mapCopy
现在可以很简单:
export const mapCopy = (object, callback) => {
return Object.keys(object).reduce(function (output, key) {
output[key] = callback.call(this, object[key]);
return output;
}, {});
}
基本上,code> mapCopy 是信任其呼叫者做正确的事情。这就是为什么我说这个假设你控制所有的呼叫站点。
Essentially, mapCopy
is trusting its callers to do the right thing. This is why I said this assumes you control all call sites.
这篇关于使用扩展符号深入复制ES6的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!