0

I'm looking for a solution to add multiple values to the same key in the map

Below is the requirement:

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

the values for key and value looks like below:

[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. Now I want to append the value of duplicate key to the existing key. Is there a way to achieve it in 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?

1
  • You want result as an array or map? Commented May 13, 2020 at 6:02

2 Answers 2

1

You need to check if there is an entry with the desired 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)
}
Sign up to request clarification or add additional context in comments.

Comments

1

Ideally what you are encountering is not a problem, since keys of a Map are meant to be unique.

To append what you can do is, accumulate your object and set it in the end.

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.

Hope it helps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.