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} }
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.
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.
Deep merging ensures that all levels of the objects we merge into another object are copied instead of referencing the original objects.
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.
You want a deep extend
$.extend(true, {}, x, y);
See the docs for jQuery.extend([deep], target, object1[, objectN])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With