[Chartjs]-Using Object.assign to merge objects

3👍

The point that you’re missing is that Object.assign does a shallow copy of the properties of the provided objects.

Both xOptions and yOptions are objects with a single property: scales, so the one on yOptions (which comes after xOptions in the parameter list) wins out.

The relevant line in the MDN documentation is here:

Properties in the target object will be overwritten by properties in the sources if they have the same key. Later sources’ properties will similarly overwrite earlier ones.

To solve this, you’ll either need a deep merge (which isn’t as simple as using Object.assign) or, if you’re only concerned about the scales property, you can merge that instead of the objects themselves.

chartOptions.scales = Object.assign(
    {}, 
    chartOptions.scales,
    xOptions.scales, 
    yOptions.scales
);

1👍

AFAIK, there is no way on Javascript to do that automatically. Instead, you can create a new object and include the attributes of the original ones. The problem arises when some attributes are repeated, what should be the value in the merged object? It is up to the application logic (the sum of both, the maximum, etc).

An approach would be:

let result = {};
let keys = new Set(Object.keys(obj1))
Object.keys(obj2).map(x => keys = keys.add(x))

keys.forEach(x => {
    result[x] = (obj1[x] || 0) + (obj2[x] || 0);
})

You can take a look at this thread for a similar question: JavaScript/Coffeescript sum objects

Leave a comment