I am trying to find a best way to update object property values which are on Map, however it seems like there isn't a specific function for this.
Example:
const map = new Map();
map.set('kfwwwdvh', { first: 1, second: 2});
Now I would like to update 'first' property value, but if I do this
map.set('kfwwwdvh', { first: 'updated value'});
It will output this:
{ first: 'updated value'}
My question is how do I update object property values without overwriting other values the object has (in this example 'second' property and value), what is the best way to achieve this?
I am trying to find a best way to update object property values which are on Map, however it seems like there isn't a specific function for this.
Example:
const map = new Map();
map.set('kfwwwdvh', { first: 1, second: 2});
Now I would like to update 'first' property value, but if I do this
map.set('kfwwwdvh', { first: 'updated value'});
It will output this:
{ first: 'updated value'}
My question is how do I update object property values without overwriting other values the object has (in this example 'second' property and value), what is the best way to achieve this?
Share Improve this question edited Oct 9, 2020 at 10:34 Kristjan Ranna asked Oct 9, 2020 at 10:21 Kristjan RannaKristjan Ranna 531 silver badge5 bronze badges2 Answers
Reset to default 4You can update the property by first retrieving the object from the map using .get()
, and then update the property of the returned object reference like so:
const map = new Map();
map.set('kfwwwdvh', { first: 1, second: 2});
map.get('kfwwwdvh').first = 'updated value';
console.log(map.get('kfwwwdvh'));
This will update the actual object in place, meaning if any references of it reside anywhere they will also be updated. This may be a good or bad thing depending on what behaviour you're after. For example:
const map = new Map();
map.set('kfwwwdvh', { first: 1, second: 2});
const obj = map.get('kfwwwdvh');
map.get('kfwwwdvh').first = 'updated value';
console.log(map.get('kfwwwdvh'), obj); // both updated
The only way is to set the value on the map key by overriding that first
value as follows.
map.set('kfwwwdvh', {
...map.get('kfwwwdvh'),
first: 'updated value'
});
const map = new Map();
map.set('kfwwwdvh', { first: 1, second: 2});
console.log(map.get('kfwwwdvh'));
map.set('kfwwwdvh', {
...map.get('kfwwwdvh'),
first: 'updated value'
});
console.log(map.get('kfwwwdvh'));