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' }

14th Jun 2022, 7:19 PM
Kate
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(), ]);
14th Jun 2022, 10:16 PM
ODLNT
ODLNT - avatar
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Ā².
14th Jun 2022, 8:00 PM
Justice
Justice - avatar
0
It does not mater i try modify myMap, but I can not, it does not work. Any others solutions?
14th Jun 2022, 8:24 PM
Kate
0
var myMap if you want 'var resullt'
14th Jun 2022, 8:34 PM
Kate
0
I found solution: listOfFirst.forEach(item => { myMap = { ...myMap, [item]: code }; }); console.log('myMap = ', myMap);
14th Jun 2022, 9:01 PM
Kate
- 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.
14th Jun 2022, 8:26 PM
Justice
Justice - avatar