JavaScript Cloning an Object
HTML-код
- Опубликовано: 13 июл 2024
- JavaScript: Cloning an Object
🔥Get the COMPLETE course (83% OFF - LIMITED TIME ONLY): bit.ly/2M1sp4B
Subscribe for more videos:
/ @programmingwithmosh
Want to learn more from me? Check out my blog and courses:
programmingwithmosh.com
/ programmingwithmosh
/ moshhamedani
Nice and clean with clear visible font size and without any intro music.
Perfect way to make coding tutorial videos.
Beautiful syntax! Thank you for showing that!
Hi Mosh... Both Object.assign and spread operator work fine for single level object like circle but what about multi level object like var obj= { a :1,b: { c:2,d:3 },e:4}. I think it will not work for multi level object. Am i right?
const another = JSON.parse( JSON.stringify(circle) )
Man your the best , keep up the good work.
thanks very much you are brilliant ..i hope you do an advance d js tutorials
Thank you sir for that video It's very helpful for us
Wow. You are genious
Great.....bro 🔥🔥🔥
where is deep cloning?shallow copy and deep copy?
You can use factory functions and Object.assign() to make beautiful compositions between objects!
Composition is far more superior than inheritance.
Another method to copy things in JS is to use JSON.parse( JSON.stringify( myObject ) )
This is probably the best way to copy all objects, because it does copy "deep" objects
can you tell me the source where i can learn about this ?
@@kaziupir it is not, it breaks with functions and circular references
@@giulioambrogi5413 what's the best way to deep clone in your opinion ?
@@emreozgun3846
//Deep clone a object
const test = {
past: [{day:31}, {month:12}, {year:2020}],
present: [{day:1}, {month:6}, {year:2021}]
}
function deepClone(input) {
let result = Array.isArray(input) ? [] : {};
if(typeof(input) !== 'object') {
return input;
}
for(const key in input) {
//console.log(input[key])
result[key] = deepClone(input[key])
}
return result;
}
console.log(deepClone(test));
if someone wants to make an dinamic object from a form using express (o well, this is just basic js xD) use something like this:
const obj = JSON.parse(JSON.stringify(req.body));
let objectToUpdate = {}
for (let field in obj) {
if (obj[field] !== ''){
objectToUpdate[field] = obj[field]
}
}
I had a little trouble doing this cause i am stupid XD Thanks mosh for just exist in this world ❤
hi Mosh - how can we use Object.assign to clone and merge objects with the *same property name* without getting them overwritten?
In this video we see the shallow copy, what you want to do is called deep copy!! On RUclips there are a lot of videos
This seems to only make a reference to the original. What if I need to make an actual copy of an object, so that I can change the copy without changing the original?
what about deep cloning an object
Exactly, the showed methods do not cover deep cloning at all
For convenience (sacrificing some speed for simplicity), or an unknown object structure, the most efficient way is by doing the following:
let clonedObject = JSON.parse(JSON.stringify(originalObject))
If your object contains Date() objects as values, they will be converted into ISO strings. If your object contains functions as values, they will be removed. In either of these cases, you will want to use a different solution, or to simply manually re-attach these values after the clone if you know the structure.
For speed, assuming you know the object structure, the most efficient way by far is doing the following:
let clonedObject = {
knownProp: originalObject.knownProp,
..
};
This of course can get large and tedious, but in terms of performance is very fast. I hope this helped.
Define your original object in a function and return it. Each time that function is called, your object will be redeclared and initialised, thereby creating new reference.
E.g
Function objSkeleton(){
return {
Name: "default Name",
Age: "default Age",
Friends: [
{name: "friend's name", age: "friend's age"},
{name: "friend's name", age: "friend's age"}
]
}
}
Const ben = objSkeleton();
ben.name = "Ben";
ben.friends[0].name = "Kyle";
Const doe = objSkeleton();
doe.name = "Doe";
doe.age = 30;
console.log(ben);
console.log(doe);
it's just copy the property right? The main objective is to deep clone and copy prototype.
How to clone an image object into array slots?
shown methods create a shallow copies, not deep ones
why not const another=circle; ??????????
its not working
const circle = {
radius: 1,
draw() {
console.log('draw');
}
};
const another = ( ...circle );
console.log(another);
Output:
Uncaught SyntaxError: Unexpected token '...'
Not even one word about shallow copy and deep copy...................................
this seems like it could be simplified why is the syntax of coding so unessesary complicated? also what is an object and why would you want to copy it.. if you make it basic tutorial remember that you can ofthen be even more basic .. imagine your audience is a group of 10 year olds..
lol me
let a = { }
let b= { ...a}
Bad, bad!!! What if object contains another object??? This video makes you think that entire object is cloned. Well, only the first level. Other levels are still references.
this is shallow copy!
i don't understand nothing in this video ,you going so fast in this one , i see him hard and less useful in project