Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prevent object and arrays modification in javascript

as you know, in javascript objects and arrays are send by reference and if we got something like this:

const obj=[{room:5},{room:35},{room:25},{room:15}];

static test(obj)
  {
    for (let i=0;i<obj.length;i++)
    {
      obj[i].room++;
    }
    return obj;
  }
return {ok:true,D:obj,R:this.test(obj)};

then the first object values would change after calling test, the question is how to prevent passing the object by reference and its modifications !??!

like image 667
Godfather Avatar asked Aug 09 '26 07:08

Godfather


1 Answers

You can use a copy of your object or your array:

Object

const copy = JSON.parse(JSON.stringify(obj))

Array

const copy = array.slice(0)
like image 179
G.aziz Avatar answered Aug 11 '26 20:08

G.aziz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!