Skip to content

The set function modifies the initial object #473

@a1r93

Description

@a1r93

Hi,

The docs state that the set function does not modify the given initial object, but that's actually only true on the first level of depth of an object.
When setting a value of a deeply nested property, the original object gets mutated, see example below:

const flatObject = {
  some: "test",
};
const updatedFlatObject = set(flatObject, "some", "updated");
// updatedFlatObject: { "some": "updated" }
// flatObject: { "some": "test" } -> OK: the original object is not mutated
console.log(flatObject, updatedFlatObject);

const nestedObject = {
  some: {
    nested: {
      object: "test",
    },
  },
};
const updatedNestedObject = set(
  nestedObject,
  "some.nested.object",
  "updated",
);
// updatedNestedObject: {some: {"nested":{"object":"updated"}}}
// nestedObject: {some: {"nested":{"object":"updated"}}} -> NOK: the original object got mutated
console.log(updatedNestedObject, nestedObject);

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions