Hey ladies and gents. I’ve seen plenty of Javascript online material describing how to access an object’s key-value pair. I wanted to associate many keys represented as variables to many values represented as functions. Variables helps make my program more reusable and dynamic. Just another day in the life of me. 🙂
Example:
var love=’yes’, loveMe=’yesYes’, loveMeMore=’OFCOURSE!’;
var kvObj = {love:foo, loveMe: foo3, loveMeMore:foo4};
function foo(){
console.log(‘foo’);
}
function foo3(which){
kvObj.which();
}
function foo4(which){
kvObj[which]();
}
Calling the function in foo3 or foo4 will not work.
So I created this very short function to help me with this:
function appendJSONData(obj, key, value){
obj [key] = value;
return obj;
}
Now if I initialize kvObj this way, calling the function in foo4 will succeed. PROFIT!!! Hope this helps!
var kvObj = {};
appendJSONData(kvObj,love,foo4);