简体   繁体   English

如何在不改变原始版本的情况下创建 object 的深度冻结版本?

[英]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.

相关问题 如何在对象的嵌套数组中添加对象而不改变原始源 - how to add object in nested array of objects without mutating original source 如何在不更改原始数组的情况下破坏对象属性? - How do i destruct object properties without mutating original array? 如何在不更改原始数组的情况下更改对象Key - How to change an object Key without mutating original array 如何在不更改原始数组的情况下过滤嵌套数组? - How can I filter a nested array without mutating the original array? 如何在不改变原始数组的情况下对数组进行排序? - How can you sort an array without mutating the original array? 如何将数组传递给函数而不改变原始数组? - How to pass an array to a function without mutating the original array? 如何在Redux中更改嵌套对象而不对其进行更改 - How to change nested Object without mutating it in Redux 如何在不改变对象的情况下更改对象的属性? - How to change a property on an object without mutating it? 一个 map 如何创建一个数组以创建一个具有更改数组项但不改变原始数组或其任何项的新数组? - How does one map an array in order to create both a new array with changed array items but without mutating the original array or any of its items? 如何创建一个新的 Object 而不是对其进行变异 - javascript? - How to create a new Object instead of mutating it - javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM