简体   繁体   中英

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. Is the only way to do a deep copy?

I know questions on how to copy an object are answered a lot on here. I'm asking if there is another way to keep this function pure:

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.

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.

If you want to change object properties you can create new objects for the property

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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