-1

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);
adnan ali
  • 33
  • 6
  • 2
    Does this answer your question? [How do I correctly clone a JavaScript object?](https://stackoverflow.com/questions/728360/how-do-i-correctly-clone-a-javascript-object) – Konrad Dec 12 '22 at 18:48
  • Instead of `const b = a`, `const b = globalThis.structuredClone(a)`. – jsejcksn Dec 12 '22 at 18:50

2 Answers2

2

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

const b = {...a}

h.howard
  • 96
  • 4
2

Use Object.freeze() to prevent modifying an object.
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}
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313