unicorn/prefer-structured-clone

Require structuredClone() for deep clones

has suggestions

JSON.parse(JSON.stringify(value)) turns a Date into a string, drops undefined, turns a Map or Set into {}, and throws on an object that refers to itself. structuredClone() is built in and copies all of these correctly, so you don't need a library function such as lodash's cloneDeep either.

Configure#

Off by default. To turn it on:

bunfig.toml
[lint.rules]
"unicorn/prefer-structured-clone" = "error" # or "warn"

Every option, set to its default:

bunfig.toml
[lint.rules]
"unicorn/prefer-structured-clone" = ["error", {
  functions = ["cloneDeep", "utils.clone"],
}]

Examples#

example.js2 problems
const draft = JSON.parse(JSON.stringify(settings));
const backup = _.cloneDeep(settings);
example.jsNo problems
const draft = structuredClone(settings);

Options#

OptionDefaultWhat it does
functions["cloneDeep", "utils.clone"]Names of functions to report. The list replaces the default.

A name with a dot, such as utils.clone, only matches that object and method. A name without a dot matches a call to that function, and a method with that name on any object.

example.jswith { "functions": ["deepCopy"] }1 problem
const draft = deepCopy(settings);
example.jswith { "functions": ["deepCopy"] }No problems
const backup = _.cloneDeep(settings);

When not to use it#

structuredClone() throws on functions and DOM nodes, and the copy of a class instance is a plain object. If you clone values like that, keep your own function.