agriz
0
Q:

object.assign

const obj = { a: 1 };
const copy = Object.assign({}, obj);
console.log(copy); // { a: 1 }
5
var person={"name":"Billy","age":34};
var clothing={"shoes":"nike","shirt":"long sleeve"};

var personWithClothes= Object.assign(person, clothing);//merge the two object
3
//Object.assign() method is for copying methods/props of one object to another
//creating 3 object constructors and assigning values to it
var obj1 = { a: 10 }; 
var obj2 = { b: 20 }; 
var obj3 = { c: 30 }; 
  
//creating target object and copying values and properties to it using object.assign() method
var new_obj = Object.assign({}, obj1, obj2, obj3); 
  
//Displaying the target object
console.log(new_obj); 

3
The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the target object.
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };

const returnedTarget = Object.assign(target, source);

console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }

console.log(returnedTarget);
// expected output: Object { a: 1, b: 4, c: 5 }
0
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };

const returnedTarget = Object.assign(target, source);

console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }

console.log(returnedTarget);
// expected output: Object { a: 1, b: 4, c: 5 }
0
'use strict';

// Merge an object
let first = {name: 'Tony'};
let last = {lastName: 'Stark'};
let person = Object.assign(first, last);
ChromeSamples.log(person);
// {name: 'Tony', lastName: 'Stark'}
ChromeSamples.log(first);
// first = {name: 'Tony', lastName: 'Stark'} as the target also changed

// Merge multiple sources
let a = Object.assign({foo: 0}, {bar: 1}, {baz: 2});
ChromeSamples.log(a);
// {foo: 0, bar: 1, baz: 2}

// Merge and overwrite equal keys
let b = Object.assign({foo: 0}, {foo: 1}, {foo: 2});
ChromeSamples.log(b);
// {foo: 2}

// Clone an object
let obj = {person: 'Thor Odinson'};
let samp = {person: 'ashok'}; 
let clone = Object.assign({}, obj, samp);
ChromeSamples.log(clone);

// {person: 'Thor Odinson'}
0
var sheep={"height":20,"name":"Melvin"};
var clonedSheep=JSON.parse(JSON.stringify(sheep));

//note: cloning like this will not work with some complex objects such as:  Date(), undefined, Infinity
// For complex objects try: lodash's cloneDeep() method or angularJS angular.copy() method
0

New to Communities?

Join the community