How do we merge data from an object to an existing Map
?
To create a Map
from an object we can use this:
const myMap = new Map(Object.entries(myObject));
Is there a way to do the same to an existing Map() without using for
loop?
const myObject = {
test: "blah",
ok: 123
}
const myMap = new Map(Object.entries(myObject));
const mySecondObject = {
test: "new value",
foo: "bar"
}
for(let i in mySecondObject)
{
myMap.set(i, mySecondObject[i]);
}
console.log({size: myMap.size, test: myMap.get("test"), myMap});
2
Answers
Note: the console in stackoverflow prevents Maps from being printed properly. It will work if you paste the code elsewhere.
If the objective is concise code, you can do this:
If you don’t mind creating a new merged map, you can do so like this:
You’re looking for the
Map.prototype.merge
method from the collection methods proposal, which is still in stage 1. With a polyfill, you could writeBut currently no such method exists. There are many ways to have a helper method do the enumeration of the object keys and/or iterate over them, which would allow you to avoid
for
syntax, but they’re not as straightforward: