admin管理员组文章数量:1393081
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'));
本文标签: javascriptHow to update Map object property valuesStack Overflow
版权声明:本文标题:javascript - How to update Map object property values? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744743769a2622767.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论