简体   繁体   English

如何在 javascript 中的纯 function 中更新 object?

[英]How do you update an object in a pure function in javascript?

I'm trying to figure out the best way to make a function pure that relies on updating an object.我试图找出依赖于更新 object 的 function 纯的最佳方法。 Is the only way to do a deep copy?是做深拷贝的唯一方法吗?

I know questions on how to copy an object are answered a lot on here.我知道关于如何复制 object 的问题在这里得到了很多解答。 I'm asking if there is another way to keep this function pure:我问是否有另一种方法来保持这个 function 纯净:

function changeId(item: ObjectWithId): ObjectWithId {
  // Not pure
  item.id = 1;
  return item;
}

Is the only way a deep copy?唯一的方法是深拷贝吗?

function changeId(item: ObjectWithId): ObjectWithId {
  const newItem = deepCopy(item);
  newItem.id = 1;
  return newItem;
}

The standard is to use the spread operator标准是使用扩展运算符

function changeId(item: ObjectWithId): ObjectWithId {
  return { ...item, id: 1 };
}

It copies all the properties to a new object and you can have a list of property overrides.它将所有属性复制到一个新的 object 并且您可以拥有一个属性覆盖列表。

You don't need a deep copy as you have not mutated the original input, even if the properties are objects you can reuse them as properties on the new object if you have not mutated them.您不需要深拷贝,因为您没有改变原始输入,即使属性是对象,如果您没有改变它们,您也可以将它们作为新 object 上的属性重用。

If you want to change object properties you can create new objects for the property如果要更改 object 属性,可以为该属性创建新对象

{
  ...originalObject,
  changedProperty: { ...originalObject.changedProperty, propertyToChange: newValue }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM