[英]How to create a deep frozen version of an object without mutating the original?
Let's say we have the following object:假设我们有以下 object:
"use strict"; // To trigger errors on frozen objects mutation attempts
const myObj = {
rootProp1: {
leafProp1: "hello",
leafProp2: "world",
rootProp2: "!",
};
When using the "classic" Object.freeze
method, we only freeze the root properties of an object:当使用“经典”
Object.freeze
方法时,我们只冻结 object 的根属性:
const frozen = Object.freeze(myObj);
frozen.rootProp2 = "?"; // error --> OK
delete frozen.rootProp1; // error --> OK
frozen.extraRootProp = "how are you?"; // error --> OK
frozen.rootProp1.leafProp1 = "hi"; // NO ERROR --> I don't want this
In order to deep freeze the object, we can use a method like this one :为了深度冻结 object,我们可以使用如下方法:
const deepFrozen = deepFreeze(myObj);
deepFrozen.rootProp1.leafProp1 = "hi"; // error --> OK
myObj.rootProp2 = "?"; // ERROR --> I don't want this
But that's still a problem for me: I would like a function that can return the frozen version of an object, without freezing the original one (I'm trying to learn functional programming so I want as less mutations as possible).但这对我来说仍然是一个问题:我想要一个 function 可以返回 object 的冻结版本,而不冻结原始版本(我正在尝试学习函数式编程,所以我想要尽可能少的突变)。 How to do that?
怎么做?
In ECMAScript 2018 (ES9), thanks to the spread operator , it's possible to use this simple function:在 ECMAScript 2018 (ES9) 中,由于展开运算符,可以使用这个简单的 function:
const deepFreeze = (obj) => typeof obj === "object"
? Object.freeze({
...Object.entries(obj).reduce(
(prev, [key, value]) => ({
...prev,
[key]: value ? deepFreeze(value) : value,
}),
{}
),
})
: typeof obj === "function" ? Object.freeze(obj) : obj;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.