Deep spread operator

There is no standardized way for creating deep copy of object. Nowadays developers have to use cloning functions from external libraries or implement them by themselves.

I propose to add deep spread operator to EcmaScript standart. This operator would extend features of regular spread operator with the difference that always will return recursive copy of its operand.

Proposed operator could have the following syntax:

const deepCopy = {...#obj};
const obj = {
  nestedArray: [1, 2, 3]
};

const shallowCopy = {...obj};
const deepCopy = {...#obj};

console.log(shallowCopy.nestedArray === obj.nestedArray); // true
console.log(deepCopy.nestedArray === obj.nestedArray); // false

you can do some of that already with JSON.parse(JSON.stringify(...))

const obj = {
   nestedArray: [1, 2, 3]
};

const deepCopy = JSON.parse(JSON.stringify(obj));

drawback of current method is it won't properly clone datatypes undefined, bigint, symbol, (and exotic-objects set, map, weakmap, regexp, etc.).

how would your proposal handle deep-cloning pathological-cases llike map and set?

let obj = new Map();
obj.set(new Set(), new Set());
obj.set(new Set(), new Set());
// obj = Map { Set {} => Set {}, Set {} => Set {} }

let deepCopy = {...#obj}
// deepCopy = ???
1 Like

I like the idea, however what's the reason for the ...# syntax? I think there are rather more intuitive ones, e.g. ...expression..., and the # is already used for private fields so that causes confusion.

This is good question. I think in Map case both keys and values should be copied by value. For abovementioned expample each new Set() key would be replaced with its deep copy in resulting deepCopy object.

Hi, selected syntax for new operator is not final and was only given as an example. So, I don't mind changing it.