TASIOMIND.DEV — OPERATIONAL▸▸▸FULL STACK DEVELOPER @ GWQ SERVICEPLUS AG▸▸▸FOUNDER — K8SGPT.AI▸▸▸OPEN SOURCE: ACTIVE▸▸▸DISTRIBUTED SYSTEMS / KUBERNETES / AI▸▸▸RUST + GO + PYTHON▸▸▸FIELD TESTED / STATUS — NOMINAL▸▸▸LOCATION: EUROPE/BERLIN▸▸▸TASIOMIND.DEV — OPERATIONAL▸▸▸FULL STACK DEVELOPER @ GWQ SERVICEPLUS AG▸▸▸FOUNDER — K8SGPT.AI▸▸▸OPEN SOURCE: ACTIVE▸▸▸DISTRIBUTED SYSTEMS / KUBERNETES / AI▸▸▸RUST + GO + PYTHON▸▸▸FIELD TESTED / STATUS — NOMINAL▸▸▸LOCATION: EUROPE/BERLIN▸▸▸

Pure ways of editing objects and arrays in JavaScript

August 6, 2020

tl;dr: use speard operator for both arrays and objects for consistent syntax. Alternatives are Obect.assign() and Array.concat()


Objects

Copying objects

code
const original = { a: 1, b: 2 };

// Object.assign()
const copy1 = Object.assign({}, original);

// Spread operator
const copy2 = { ...original };

extending objects

code
const original = { a: 1, b: 2 };
const extension = { c: 3 };

// Combine multiple objects with Object.assign()
const extendedCopy1 = Object.assign({}, original, extension);

// Combine multiple objects with Spread operator
const extendedCopy2 = { ...original, ...extension };

Arrays

Copying arrays

code
// Copy array
const original = [1, 2, 3];

// .slice() with no args
const copy = [1, 2, 3].slice();

extending arrays

code
const original = [1, 2, 3];

// Array.concat() returns a new array
const extended = original.concat(4);
const moreExtended = original.concat([4, 5]);

// Spread operator
const extended2 = [...original, 3, 4];
const moreExtended2 = [...original, ...extended2];

fyi: according to an article, Array.push() is 945x faster than Array.concat()