I am adding values to a map. I checked if values are filled still when i try to get the values from the map by key I get: undefined in de console.log


const mapAcc = new Map();
var accId =res.split(' Id=');
var accName =res.split(' Name=');
for (let i = 1; i < accId.length; i++) {
mapAcc[accId[i].substring(0,18)] = accName[i].split(',')[0];
console.log('mapAcc: ' + mapAcc.get('0018E0000XXXXXXXX'));

1 Answer 1


You need to use the set method to set a value in a Map:

mapAcc.set(accId[i].substring(0,18), accName[i].split(',')[0]);

Using the object[key] notation instead sets Object properties on the Map that are not part of the Map's data structure, as noted on MDN:

Setting Object properties works for Map objects as well, and can cause considerable confusion.

Therefore, this appears to work in a way:

const wrongMap = new Map();
wrongMap['bla'] = 'blaa';
wrongMap['bla2'] = 'blaaa2';

console.log(wrongMap); // Map { bla: 'blaa', bla2: 'blaaa2' }

But that way of setting a property does not interact with the Map data structure. It uses the feature of the generic object. The value of 'bla' is not stored in the Map for queries. Other operations on the data fail:

wrongMap.has('bla')    // false
wrongMap.delete('bla') // false
console.log(wrongMap)  // Map { bla: 'blaa', bla2: 'blaaa2' }

The correct usage for storing data in the Map is through the set(key, value) method.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .