const a = {x: "Hi", y: "Test"}
const b = ???
// b = {x: "Bye", y: "Test"}
// a = {x: "Hi", y: "Test"}
Try this : const b = a.map(item => Object.assign({}, ...item));
This will create a new object without any reference to the old object a
In case if you want to do this for an array try the same with []
const b = a.map(item => Object.assign([], ...item));
there's an easy way to change object property without mutating the original object.
const a = {x: "Hi", y: "Test"};
const b = {...a, y: "hello"};
Two ways...
You can use Object.assign:
const a = { x: "Hi", y: "Test" }
const b = Object.assign({}, a, { x: "Bye" });
console.log(b);
Or you can use the object spread operator.
The spread operator allows you to "assign" all properties of one object to another.
We can use it here within an object literal to assign all properties of a
to b
:
const additions = { x: "Bye" }
const a = { x: "Hi", y: "Test" }
const b = { ...a, ...additions }
console.log(b);
Es6 has a built in function for copying object properties, Object.assign
const b = Object.assign({}, a, {x: 'Bye'})
here we create an empty object, push all of a
s key value pairs in, followed by the new key value pairs we want to over write. because the empty object is the first argument, we mutate that object, not a
Create a copy of the object and change the copy:
const b = Object.assign({}, a, {x: "Bye"})
Docs for Object.assign()