Godfather
Godfather

Reputation: 372

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 !??!

Upvotes: 3

Views: 2704

Answers (1)

Aziz.G
Aziz.G

Reputation: 3721

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)

Upvotes: 5

Related Questions