最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to update Map object property values? - Stack Overflow

programmeradmin0浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 4

You 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'));

发布评论

评论列表(0)

  1. 暂无评论