0
How can I create new map and merge with first
var myMap = { 17035: "box", 93133: "box", 97872: "bag", }; const code = "packet"; const listOfFirst = [92327, 91278]; var newMap = new Map(); listOfFirst.forEach(item => newMap.set(item, code)); const resullt = new Map([ ...myMap, ...newMap, ]); I try to get: const resullt = { 17035: 'box', 93133: 'box', 97872: 'bag', 92327: 'packet', 91278: 'packet' }
6 Answers
+ 1
const resullt = new Map([
...myMap,
...newMap,
]);
The Map constructor accepts an array or array-like collection of key-value pairs.
With snippet as-is, you are trying to pass the constructor a plain object and a Map object.
You can convert the myMap and newMap to an iterator of key-value pairs.
By doing so you will then be able to use the spread operator to pass them to the Map constructor.
should be
const resullt = new Map([
...Object.entries(myMap),
...newMap.entries(),
]);
0
You can try a less than ideal time complexity solution where you just create a new map, then go over the contents of each map you want to add with a loop, and add individually to the new map.
Though you're most likely going to use a nested loop so it'll have terrible time complexity. Probably like log nÂČ.
0
It does not mater i try modify myMap, but I can not, it does not work. Any others solutions?
0
var myMap
if you want 'var resullt'
0
I found solution:
listOfFirst.forEach(item => {
myMap = {
...myMap,
[item]: code
};
});
console.log('myMap = ', myMap);
- 1
That's because you have it as a constant. Remember, constants cannot be changed.
edit: I got this mixed up with Java, sorry about that.