How can I change the **obj2 **values instead of doing it one by one as shown is there a way that doing it at once ?
const obj1={
name:`serag`,
age:30,
children:
{
daughter:`leila`,
son:`seif`
}
};
const obj2 = JSON.parse(JSON.stringify(obj1));
let {name,age,children}=obj2;
// obj2.name =`omar`;
// obj2.age=30;
// obj2.children.daughter=`huda`;
// obj2.children.son=`ahmed`;
How can I change the **obj2 **values instead of doing it one by one as shown is there a way that doing it at once ?
const obj1={
name:`serag`,
age:30,
children:
{
daughter:`leila`,
son:`seif`
}
};
const obj2 = JSON.parse(JSON.stringify(obj1));
let {name,age,children}=obj2;
// obj2.name =`omar`;
// obj2.age=30;
// obj2.children.daughter=`huda`;
// obj2.children.son=`ahmed`;
One of the many ways is to use spread operator.
const obj3 = {...obj1}
You can also use Object.assing() for shallow copy.
const shallowCopy = Object.assign({}, obj1);
For more information please have a look at this.
Hope, this helps.
You can use object assign to clone and modify the object at once.
// obj1
const obj2 = Object.assign({}, obj1, {
name: "omar",
age: 35,
children: Object.assign({}, obj1.children, {
daughter: "huda",
son: "ahmed",
}),
});