Reputation: 23
I know there are some similar questions, but non of them could not help me with my issue:
I have an Object:
var mapOptions = {
legend: {
data:[
{name: 'Europe', backgroundColor: 'RGB(228,101,41)'},
{name: 'APAC', backgroundColor: 'RGB(0,71,126)'},
{name: 'MENEAT', backgroundColor: 'RGB(145,0,73)'}
],
}
}
This object should be updated by this object:
var newOptions = {
legend: {
data: [
{name: 'Europe', backgroundColor: 'green'},
]
}
}
What should the update function be able to do:
Update attributes: From 'RGB(228,101,41)'
to 'green'
Delete do not needed items: E.g. Only 'Europe'
item should remain.
For now I use the jQuery extend/deep
function:
$.extend(true, mapOptions, newOptions);
It works partly. Only the Attributes are updated.
Can anybody help me to achieve the second point, how to delete/add items?
Or should I split it in 2 functions better?
Thank you for any help!
Upvotes: 1
Views: 71
Reputation: 386578
For more than one item to update, you could use a hash table with a reference to the objects and iterate then the update array.
If hash
is set for a given name, update, otherwise push the new object to the array.
var mapOptions = { legend: { data: [{ name: 'Europe', backgroundColor: 'RGB(228,101,41)' }, { name: 'APAC', backgroundColor: 'RGB(0,71,126)' }, { name: 'MENEAT', backgroundColor: 'RGB(145,0,73)' }], } },
newOptions = { legend: { data: [{ name: 'Europe', backgroundColor: 'green' }, ] } },
hash = Object.create(null);
mapOptions.legend.data.forEach(function (a, i) {
hash[a.name] = a;
});
newOptions.legend.data.forEach(function (a) {
if (hash[a.name]) {
hash[a.name].backgroundColor = a.backgroundColor;
} else {
mapOptions.legend.data.push(a);
}
});
console.log(mapOptions.legend.data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 0
Reputation: 595
Try this
mapOptions.legend.data = {name: 'Europe', backgroundColor: 'green'};
Upvotes: 0
Reputation: 133370
If you want just change the first valeus You could use the relative index position (0) inside the data array
mapOptions.legend.data[0] = {name: 'Europe', backgroundColor: 'green'};
if the you want change all the data contente then you can use the javascript dot notation for accessing object element
mapOptions.legend.data = {name: 'Europe', backgroundColor: 'green'};
Upvotes: 1
Reputation: 2916
Based on your example, the solution could be a basic assignment:
mapOptions.legend.data = newOptions.legend.data
Upvotes: 1