0
Q:

javascript merge objects

const object1 = {
  name: 'Flavio'
}

const object2 = {
  age: 35
}
const object3 = {...object1, ...object2 } //{name: "Flavio", age: 35}
32
var student = {name: "Rahul", age: "16", hobby: "football"};

//using ES6
var studentCopy1 = Object.assign({}, student);
//using spread syntax
var studentCopy2 = {...student}; 
//Fast cloning with data loss
var studentCopy3 = JSON.parse(JSON.stringify(student));
6
var person={"name":"Billy","age":34};
var clothing={"shoes":"nike","shirt":"long sleeve"};

var personWithClothes= Object.assign(person, clothing);//merge the two object
3
const obj1 = {'a': 1, 'b': 2};
const obj2 = {'c': 3};
const obj3 = {'d': 4};

const objCombined = {...obj1, ...obj2, ...obj3};
1
const a = { b: 1, c: 2 };
const d = { e: 1, f: 2 };

const ad = { ...a, ...d }; // { b: 1, c: 2, e: 1, f: 2 }
5
/* For the case in question, you would do: */
Object.assign(obj1, obj2);

/** There's no limit to the number of objects you can merge.
 *  All objects get merged into the first object. 
 *  Only the object in the first argument is mutated and returned.
 *  Later properties overwrite earlier properties with the same name. */
const allRules = Object.assign({}, obj1, obj2, obj3, etc);
0
const object1 = {
  name: 'Flavio'
}

const object2 = {
  age: 35
}

const object3 = {...object1, ...object2 }
0

New to Communities?

Join the community