Skip to content

Object Assign

Why Object.assign ?

If the properties in the target object have the same key, the resources will be overwritten. Then the characteristics of the resources will similarly overwrite the previous ones.

The Object.assign () method can only be enumerated and copies its properties from a source object to a target object. [[Get]] is used as the source and [[Set]] is used as the destination. Returns the target object with properties and values ​​copied from the target object. Object.assign () does not throw to empty or undefined resource values.

Syntax:

Object.assign(target, …sources)

target : It is the target object from which values and properties have to be copied.
sources : It is the source object to which values and properties have to be copied.


Notice in the following example how we use an empty object literal and copy over the properties from myObject to create a new object (myObjectTwo) that’s a copy of myObject:

        let myObject = {
            name: "rick",
            animal: "dog",
            fruit: "apple",
            job: "doctor"
        }

        let myObjectTwo = Object.assign({}, myObject);

        console.log(Object.is(myObject, myObjectTwo));
        console.log(myObjectTwo);

output:

false
{name: “rick”, animal: “dog”, fruit: “apple”, job: “doctor”}

only one object can be copied with Object.assign of enumerable properties.

In other words;
Object.assign() is used for cloning an object.
Object.assign() is used to merge object with same properties.

You can better understand this with examples.


JavaScript Object Assign Examples

Example 1

I created two objects named per1Name (first person name) and per1Surname( first person surname ). I have combined these objects with object.assign and printed them.

        let per1Name = { name: "tom" };
        let per1Surname = { surname: "allen" };
        let person = Object.assign(per1Name, per1Surname);

        console.log("name: " + per1Name.name);
        console.log("surname:" + per1Surname.surname)

        console.log(person);
        console.log(per1Name);

output:

name: tom
surname: allen
{name: “tom”, surname: “allen”}
{name: “tom”, surname: “allen”}


Example 2

We are creating an object called mes. We are creating an element named “past” inside this object. We’re syncing this to “hello my friend”. Then, with the help of object.assign, we create the “after” element. It’s “how are you?” We’re equalizing. We combine the writing with object.assign method.

        let mes = {
            past: "hello my friend",
        }

        let arr = Object.assign(mes, { after: "how are you?" });
        console.log(arr)

output:

{past: “hello my friend”, after: “how are you?”}


Example 3

        let list1 = { a: 10, b: 20 };
        let list2 = { b: 30, c: 40 };
        let list3 = { c: 50, d: 60 };
        let list4 = { d: 70, e: 80 };

        let NewList = Object.assign({}, list1, list2, list3, list4);

        console.log(NewList);

output:

{a: 10, b: 30, c: 50, d: 70, e: 80}


Example 4

I create two objects named list1 and list2. I combine these with a method other than the object.assign method.

        let list1 = {
            num1: 11,
            num2: 22,
            num3: 33,
        }

        let list2 = {
            num4: 44,
            num5: 55,
            num6: 66
        }

        let arr = {...list1,...list2}
        console.log(arr)

output:

{num1: 11, num2: 22, num3: 33, num4: 44, num5: 55, num6: 66}
num1: 11
num2: 22
num3: 33
num4: 44
num5: 55
num6: 66


Example 5

        let people = {
            person1: "alex",
            person2: "oliver",
            person3: "rick"
        };

        let arr = Object.assign({}, people);
        console.log(arr.person1);
        console.log(arr.person2);
        console.log(arr.person3);

output:

alex
oliver
rick

Example 6

Like the 1st example. ( function )

        let per1Name = { name: "tom" };
        let per1Surname = { surname: "allen" };
        let person = {
            fullname: function () {
                return Object.assign(per1Name, per1Surname)
            }
        }

        console.log("name: " + per1Name.name);
        console.log("surname:" + per1Surname.surname)

        console.log(person.fullname());
        console.log(per1Name);

output:

name: tom
surname: allen
{name: “tom”, surname: “allen”}
{name: “tom”, surname: “allen”}


Polyfill

if (typeof Object.assign != 'function') {
  // Must be writable: true, enumerable: false, configurable: true
  Object.defineProperty(Object, "assign", {
    value: function assign(target, varArgs) { // .length of function is 2
      'use strict';
      if (target == null) { // TypeError if undefined or null
        throw new TypeError('Cannot convert undefined or null to object');
      }

      var to = Object(target);

      for (var index = 1; index < arguments.length; index++) {
        var nextSource = arguments[index];

        if (nextSource != null) { // Skip over if undefined or null
          for (var nextKey in nextSource) {
            // Avoid bugs when hasOwnProperty is shadowed
            if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
              to[nextKey] = nextSource[nextKey];
            }
          }
        }
      }
      return to;
    },
    writable: true,
    configurable: true
  });
}

Browser Support

Chrome45
Edgeyes
Firefox34
Internet Explorerno
Opera32
Safari9
Android webviewno
Chrome for Android45
Edge mobile34
Firefox for Androidyes
Opera Androidno

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: