简体   繁体   English

如何将值添加到 javascript map 中的特定键?

[英]How to add values to specific key in javascript map?

I'm looking for a solution to add multiple values to the same key in the map我正在寻找一种将多个值添加到 map 中的同一个键的解决方案

Below is the requirement:下面是要求:

objs = new Map<string,obj>()
objs.set(obj.name,obj)

the values for key and value looks like below: key 和 value 的值如下所示:

[pen,{pen,red,2}],[pencil,{pencil,yellow,1}],[pen,{pen,bule,3}]

so I'm setting value based on the name.所以我根据名称设置值。 Since I'm trying set value in the map, the duplicate key is overriding the value of the pen key.由于我正在尝试在 map 中设置值,因此重复键会覆盖笔键的值。 Now I want to append the value of duplicate key to the existing key.现在我想将 append 重复键的值复制到现有键。 Is there a way to achieve it in javascript?有没有办法在 javascript 中实现它?

I'm expecting the result as below:我期待结果如下:

[pen,[{pen.red,2},{pen,blue,3}]],[pencil,{pencil,yellow,1}]

Can someone help me with this?有人可以帮我弄这个吗?

Ideally what you are encountering is not a problem, since keys of a Map are meant to be unique.理想情况下,您遇到的不是问题,因为Map的键是唯一的。

To append what you can do is, accumulate your object and set it in the end.到 append 你可以做的是,把你的 object 累加到最后。

Something like this像这样的东西

let obj = new Map();
let objToInsert = { ...add all the objects possible here };
obj.set(name, objectToInsert);

That way you can have keys with multiple objects listed inside of it.这样,您可以拥有其中列出的多个对象的键。

If you are using some loop and adding items later, you can also try out something like this如果您正在使用一些循环并稍后添加项目,您也可以尝试这样的事情

let obj = new Map();
let name = "parent";
let objToInsert = { test: "value" };
obj.set(name, objectToInsert);
someArray.forEach((_, index) => {
   obj.set(name, { ...obj.get(name), [index]: "test" });
});

meaning you will have to get items from your Map and insert it again along with your new data to have it appended.这意味着您必须从Mapget项目,然后将其与新数据一起再次插入以将其附加。

Hope it helps希望能帮助到你

You need to check if there is an entry with the desired key .您需要检查是否有带有所需key的条目。 Check if that's an array, if not create one, add the new value and save it.检查这是否是一个数组,如果不是创建一个,添加新值并保存它。

let existingEntry = objs.get(obj.name)

if (!existingEntry) {
 objs.set(obj.name, [obj])
} else {
 if (!Array.isArray(existingEntry)) { //this may not be needed if you have full control over the map
   existingEntry = [existingEntry]
 }
 existingEntry.push(obj)
 objs.set(obj.name, existingEntry)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM