👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!
JavaScript has an Object class which has all kinds of methods we can use to manipulate these objects. In this article, we’ll take a look at the Object.assign () method and show how it’s used.
We remind you that an object is a data type in JavaScript, similar to dictionaries in Python, which have what we call key: value pairs. Let’s say we have an item, let’s call it Harry. It can have key: value pairs similar to this:
The rule of thumb for the theme in this situation is that the name of the property to the left of the colon is the key and the things to the right are the value. Most of the keys and values ​​are pretty straightforward - the only one that can be a bit risky is the last property: pet. The pet is always the key here. The value, however, is an object that has two other key pairs: value. This is what we call a nested object.
Object.assign (target,… sourceObjs);
There is an Object method called assign () which can be used to take one or more source objects and copy them to a target object. Let’s go straight to the code to see what it does:
Let’s expose the code together. Let’s start with a literal object called hpChar. This hpChar has a first name, last name, age, domicile and pet. This pet property is an object itself and has a few keys and values ‚Äã‚Äãby itself.