org.sonar.l10n.javascript.rules.javascript.S6661.html Maven / Gradle / Ivy
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 }
.
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.
const a = {...foo};
const b = {...foo, ...bar};
const c = {foo: 123, ...bar};
const d = {};
Resources
Documentation
- MDN web docs - Spread in object
literals
- MDN web docs -
Object.assign()