32 lines
1.8 KiB
Plaintext
32 lines
1.8 KiB
Plaintext
== Why is this an issue?
|
|
|
|
When merging objects or copying properties from one object to another, use the object spread syntax instead of `Object.assign()`. The object spread syntax was introduced in ES2018 and allows shallow-cloning or merging of objects with a more concise and readable syntax.
|
|
|
|
The `Object.assign()` also allows to mutate an object, which is not possible with the spread syntax, so the rule only applies to cases where the first argument of the `Object.assign()` is an object literal.
|
|
|
|
The object spread syntax improves clarity when you're modifying an object, as demonstrated in this example: `foo = { bar: 42, ...baz }`. Additionally, it provides a more concise way to perform a shallow clone. Instead of using `foo = Object.assign({}, bar)`, you can simply write `foo = { ...bar }`.
|
|
|
|
[source,javascript,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
const a = Object.assign({}, foo); // Noncompliant: Use spread syntax to clone or merge objects
|
|
const b = Object.assign({}, foo, bar); // Noncompliant: Use spread syntax to clone or merge objects
|
|
const c = Object.assign({foo: 123}, bar); // Noncompliant: Use spread syntax to clone or merge objects
|
|
const d = Object.assign({}); // Noncompliant: Use spread syntax to clone or merge objects
|
|
----
|
|
|
|
To fix the code replace `Object.assign()` with a spread syntax.
|
|
|
|
[source,javascript,diff-id=1,diff-type=compliant]
|
|
----
|
|
const a = {...foo};
|
|
const b = {...foo, ...bar};
|
|
const c = {foo: 123, ...bar};
|
|
const d = {};
|
|
----
|
|
|
|
== Resources
|
|
=== Documentation
|
|
|
|
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax#spread_in_object_literals[Spread in object literals]
|
|
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign[``Object.assign()``]
|