In the Object.assign() method, and result visually is the same, regardless of whether [{}] is assigned or not

Asked

Viewed 78 times

0

let obj = [
    {
        id:1,
        nome:'Tony Stark'
    },

    {
        id: 2,
        nome: 'Steve Rogers'
    }
];

let clone = Object.assign([{}], obj);
let clone2 = Object.assign(obj);
console.log(clone);
console.log(clone2);

  • What is your doubt?

  • What’s the difference of including [{}] in Object.assign and without it the result is the same?

1 answer

0

In the clone you passed [{}] as source, the interpreter will understand as an empty array object and fill in with the new object.

In the clone2 you have done nothing but create a reference to the first object. If you make a change to obj it will be reflected to the clone2. It is an "incorrect way" or not ideal to do, it is the same as doing clone2 = obj.

Note the implementation of the Object.assign function():

Syntax

Object.assign(destination, ...origins)

Parameters

fate - The object destination.

origins - One or more objects of origin.

Citation

The 'destination' object will be returned.

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

Browser other questions tagged

You are not signed in. Login or sign up in order to post.