How to create Map<String,List<String>>
in Javascript?
Push method does not seem to work if we define
aMap = {} and
if(aMap [key])
{
aMap[key].push(value);//this is not working for some reason
}
You have to create the key as an array, first.
// Create an empty Object
var aMap = {};
function addValueToKey(key, value) {
// Shorcut || returns left side if it is "truthy," or the right otherwise.
// This means that we only assign a new Array to the Object's property
// if it has not previously been used.
aMap[key] = aMap[key] || [];
// Adds a value to the end of the Array
aMap[key].push(value);
}
Once browsers support the new logical nullish assignment, we can write the code more gracefully (this will apply to LWC only):
var aMap = {};
function addValueToKey(key, value) {
aMap[key] ??= [];
aMap[key].push(value);
}
Where ??=
reads "Assign the value on the right to the left, only if the left is null/undefined", and will become the new standard for someVar[key] = someVar[key] || newValue
.
??=
, which makes it even easier to read, too.