Home > OS >  how to constant object or remain object values same in javascript?
how to constant object or remain object values same in javascript?

Time:12-13

Here is basic example where I want to explain my requirement . I want not to change object a values after assigning it to const b and changing its values .I want console result original object a values not after assign values . how can I achive this in console name :abc, number 123

const a ={
name:"abc",
number:123
}
const b = a
b.name ="xyz";
b.number = 321
 console.log(a);

CodePudding user response:

simply do this with b so that b will not reference to a

const b = {...a}

CodePudding user response:

Object.freeze() might be really handy to prevent modifying an object's values. Just, before doing so you might want to (optionally) spread your original object {...a} values into b beforehand, (or by using Object.assign()) in order to keep the a object values still modifiable:

const a = {
  name: "abc",
  number: 123
};

const b = {...a};
Object.freeze(b);

a.name = "Still modifiable";
a.number = 999;
console.log(a); // {"name": "Still modifiable!", "number": 999}

b.name = "xyz";
b.number = 321;
console.log(b); // {"name": "abc", "number": 123}

  • Related