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`;
I just started to learn JS consider myself a beginner
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`;
I just started to learn JS consider myself a beginner
Share Improve this question asked Nov 17, 2024 at 16:29 MaxMax 33 bronze badges 3- What you're asking (technically) is: how to clone an object in JavaScript. There's many methods as already answered herein. But, thought this might help if you wanted to research it some more. – Joe Johnson Commented Nov 17, 2024 at 18:58
- If this data structure is supposed to represent real "people", you're likely not going to have fun with it in its current form for long ... As soon as you will encounter a person that has more than one son or more than one daughter, how are you going to stick that info into there then ...? – C3roe Commented Nov 18, 2024 at 9:50
- Really appreciates your replies, I did searched yesterday for how to shallow or deep copy before asking and all works fine the thing is how if I have a lot information in the copied object and I want to edit it without going on one by one it would be tedious to do so that's what I meant , I believe there is another way than using object but I wanted to know if it's done while using this DS first as I learn down the road @C3roe – Max Commented Nov 18, 2024 at 12:44
2 Answers
Reset to default 1One 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",
}),
});