1var student = {name: "Rahul", age: "16", hobby: "football"};
2
3//using ES6
4var studentCopy1 = Object.assign({}, student);
5//using spread syntax
6var studentCopy2 = {...student};
7//Fast cloning with data loss
8var studentCopy3 = JSON.parse(JSON.stringify(student));
1const object1 = {
2 name: 'Flavio'
3}
4
5const object2 = {
6 age: 35
7}
8const object3 = {...object1, ...object2 } //{name: "Flavio", age: 35}
9
1var person={"name":"Billy","age":34};
2var clothing={"shoes":"nike","shirt":"long sleeve"};
3
4var personWithClothes= Object.assign(person, clothing);//merge the two object
5
1const a = { b: 1, c: 2 };
2const d = { e: 1, f: 2 };
3
4const ad = { ...a, ...d }; // { b: 1, c: 2, e: 1, f: 2 }
1// reusable function to merge two or more objects
2function mergeObj(...arr){
3 return arr.reduce((acc, val) => {
4 return { ...acc, ...val };
5 }, {});
6}
7
8// test below
9
10const human = { name: "John", age: 37 };
11
12const traits = { age: 29, hobby: "Programming computers" };
13
14const attribute = { age: 40, nationality: "Belgian" };
15
16const person = mergeObj(human, traits, attribute);
17console.log(person);
18// { name: "John", age: 40, hobby: "Programming computers", nationality: "Belgian" }
19
1/**
2 * Simple object check.
3 * @param item
4 * @returns {boolean}
5 */
6export function isObject(item) {
7 return (item && typeof item === 'object' && !Array.isArray(item));
8}
9
10/**
11 * Deep merge two objects.
12 * @param target
13 * @param ...sources
14 */
15export function mergeDeep(target, ...sources) {
16 if (!sources.length) return target;
17 const source = sources.shift();
18
19 if (isObject(target) && isObject(source)) {
20 for (const key in source) {
21 if (isObject(source[key])) {
22 if (!target[key]) Object.assign(target, { [key]: {} });
23 mergeDeep(target[key], source[key]);
24 } else {
25 Object.assign(target, { [key]: source[key] });
26 }
27 }
28 }
29
30 return mergeDeep(target, ...sources);
31}
32