Bnjii Bnjii - 7 months ago 14
Javascript Question

Setting Javascript variable inside for loop

I looked at a lot of posts around global/local variables but I think I'm missing something.
This is what I'm trying to get to:

var commandList = {
'command_a': function() {
socket.emit({action: 'a'});
},
'command_b': function() {
socket.emit({action: 'b'});
}
};


Instead of defining my list of commands, I would like to define them dynamically from an ajax call.
This is my best attempt:

function getCommands() {
$.ajax({
type:'get',
url: '/getCommands',
data: data,
success: function(data) {

JSONdata = $.parseJSON(data);
// [{"action": "b", "command": "command_b"},{"action": "a", "command": "command_a"}]

var commandList = [];

jQuery.each(JSONdata, function( i, val ) {

command = val['command'];
action = val['action'];

service = {
[command]: function() {
socket.emit({action: [action]});
}
console.log(service[Object.keys(service)[0]]);
}
commandList.push(service);
});
}
});
}


The main problem is that in my loop, my
action
variable doesn't get replaced by
a
or
b
in
service
, which I assume is because
action
only gets defined when the function is called. The
console.log
returns:

function () {
socket.emit({action: [action]});
}


Instead of:

function () {
socket.emit({action: 'a'});
}

Answer

Try removing brackets surrounding action at socket.emit({action: action});. Also, console.log(service[Object.keys(service)[0]]); is outside of function body at [command]:function(){}, creating a syntax error; moved to after after service definition.

var commandList = [];

jQuery.each(JSONdata, function(i, val) {

  var command = val["command"];
  var action = val["action"];

  var service = {
    [command]: function() {
      socket.emit({action: action}); // removed brackets at value `action`
    }
  };
  console.log(service[Object.keys(service)[0]]); // moved outside of `service`
  commandList.push(service);
});

plnkr http://plnkr.co/edit/VkmPGl9lWwiPKarvrbLJ?p=preview