Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deeply merge two object values by keys

Trying to see if there is any javascript library functionality that can merge the values for a specific key of two json objects

var x ={ "student-marks":{'math':1,'physics':5} }; var y ={ "student-marks":{'chemistry':3,'history':2} }; 

using $.extend and $.merge giving below results

$.extend({},x,y)  leads to  { "student-marks":{'chemistry':3,'history':2} }  $.merge(x,y) leads to { "student-marks":{'math':1,'physics':2} } 

what I am looking for is ‍{ "student-marks":{'math':1,'physics':5, 'chemistry':3,'history':2} }‍

like image 644
Venkat Avatar asked Aug 28 '13 21:08

Venkat


People also ask

How do you combine two values of objects?

To merge objects into a new one that has all properties of the merged objects, you have two options: Use a spread operator ( ... ) Use the Object. assign() method.

Does object assign deep merge?

This is because Object. assign does a shallow merge and not a deep merge. A shallow merge means it will merge properties only at the first level and not the nested level.

What is a deep merge?

Deep merging ensures that all levels of the objects we merge into another object are copied instead of referencing the original objects.

Can we merge two objects in JavaScript?

To merge two objects in JavaScript, you can use the spread ... operator. The spread operator creates a new object with all the properties from the first and second object. If there's two properties with the same name, the property from the second object wins out.


1 Answers

You want a deep extend

$.extend(true, {}, x, y); 

See the docs for jQuery.extend([deep], target, object1[, objectN])

like image 174
Mulan Avatar answered Sep 24 '22 15:09

Mulan