Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

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
}
share|improve this question
    
Thanks @Mark Pond for editing the code snippet –  Syed Amber Iqbal yesterday

1 Answer 1

up vote 3 down vote accepted

You have to create the key as an array, first.

var aMap = {};
function addValueToKey(key, value) {
    aMap[key] = aMap[key] || [];
    aMap[key].push(value);
}
share|improve this answer
    
Thanks for the reply. This worked for me. var arr = []; arr.push(aMap[key]); arr.push(value); aMap[key]=arr; –  Syed Amber Iqbal yesterday
    
@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 yesterday
    
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; } –  Syed Amber Iqbal yesterday
    
@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 yesterday

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.