Combine two objects into one

In javascript, I would like to combine two objects into one. I got

{ test: false, test2: false } 

and

 { test2: true } 

I tried using $.extend , $.merge , but all I get as a result is

 { test2: true } 

How to get this conclusion

 { test: false, test2: true } 

EDIT: Actually, I have nested objects. I need to combine a and b as follows:

 var a = { test: false, test2: { test3: false, test4: false } }; var b = { test2: { test4: true } }; // desired combined result: { test: false, test2: { test3: false, test4: true } } 

but the actual result I get removes test3 from the test2 nested object.

+4
source share
2 answers
 var a = { test: false, test2: false }; var b = { test2: true }; var c = $.extend(a, b); 

This will overwrite all properties of object a with:

 { test: false, test2: true } 

If you want a new, fresh call to the .extend object as follows:

 var c = $.extend({}, a, b); 

This will do the same job, but does not leave object a untouched and creates a new object. See http://api.jquery.com/jQuery.extend/


Update

In your comment, you updated the structure of the objects. Well, what you need is the so-called "deep clone". This is just another parameter to call $.extend() , for example:

 var c = $.extend(true, a, b); // a gets overwritten var c = $.extend(true, {}, a, b); // new object is created 
+9
source

You can use Object.assign to copy the values โ€‹โ€‹of all enumerated own properties from one or more source objects to the target object.

I used it in this reusable object merge component that merges several objects into one without changing them.

Example:

 const o1 = { a: 1 }; const o2 = { b: 2 }; const o3 = { c: 3 }; const obj = merge(o1, o2, o3); console.log(obj); // { a: 1, b: 2, c: 3 } console.log(o1); // { a: 1 } does not mutate objects 
0
source

Source: https://habr.com/ru/post/1393956/


All Articles