3

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

1 Answer 1

7

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.

7
  • Thanks for the reply. This worked for me. var arr = []; arr.push(aMap[key]); arr.push(value); aMap[key]=arr; Commented Apr 14, 2015 at 23:17
  • @SyedAmberIqbal You're adding null to the array, then adding the value, then finally putting it into the named slot. That's not correct. A "map" in JS is {}, and an "array" is []. Start from the function above. And, FYI, this really should have been on Stack Overflow, so it'll probably be moved anways.
    – sfdcfox
    Commented Apr 14, 2015 at 23:31
  • Yeah that's right this should be the correct part of the code if(aMap[key]) { var arr = []; arr.push(aMap[key]); arr.push(value); aMap[key]=arr; } else{ aMap[key] = value; } Commented Apr 14, 2015 at 23:34
  • @SyedAmberIqbal You're still wrapping your array inside itself once the key exists. Try using my code as a base for your tests, and your Map<String, List<String>> will work.
    – sfdcfox
    Commented Apr 15, 2015 at 1:58
  • 1
    @JigarTrivedi You're just in time. There's a new operator in town, ??=, which makes it even easier to read, too.
    – sfdcfox
    Commented May 26, 2021 at 12:18

You must log in to answer this question.

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