0

As demonstrated below, it appears that Array.forEach(myObject => callback) returns myObject as a reference to the exact object in my Array. Is there any built-in or graceful way to return an unreferenced copy of myObject in an Array.forEach without calling something like myObject = _.cloneDeep(myObject) on each iteration?

Thanks.

const trades = [
  { qty: 0 },
  { qty: 2 }
];

trades.forEach((trade, index) => {
  trade.qty += 1;
  trades[index].qty += 1;
  console.log(trade);
});

console.log(trades);
yqlim
  • 6,898
  • 3
  • 19
  • 43
jboxxx
  • 707
  • 10
  • 19
  • 1
    there is not; if you want copies of the elements in your array, you need to make them yourself. – Hamms Nov 27 '19 at 01:36
  • 1
    There is no real way to do this in Javascript. If you are already using lodash, then go with one of their clone functions, JQuery has $.extend which works as well. – jacob13smith Nov 27 '19 at 01:37
  • Why not use `.map()`, and build a _new_ object every time you loop, keeping the original unchanged: `const new_trades = trades.map(({qty}) => ({qty: qty+2}));` – Nick Parsons Nov 27 '19 at 01:41
  • I'll stick with lodash's cloneDeep... thanks all – jboxxx Nov 27 '19 at 01:44

0 Answers0