-2

I have an array which I would like to turn into an object with one twist. I would like to set each key and value of the object to be the value of the index of the array which I am currently on.

$('#MoveRight').click(function () {
        var selectedUsers = $('#allUsersDD').val();
        //turn to object
    });

selectedUsers is an array

Andrew Kilburn
  • 2,251
  • 6
  • 33
  • 65

3 Answers3

1

you can do it with a single loop.

var usersObj = {};
for (var k = 0; k < selectedUsers.length; k++) {
    usersObj[k] = selectedUsers[k];
}
spac3nerd
  • 176
  • 3
1

If you have a js Array of lots of key-value pairs, you can convert it like this:

var array = [{key:"one",value:1},{key:"two",value:2},....]

var newObject = {}

for(var i = 0; i < array.length; i++){
    newObject[array[i].key] = array[i].value;
}
0
$('#MoveRight').click(function () {
  var selectedUsers = $('#allUsersDD').val();
  var obj = {};
    $(selectedUsers).each(function (i, v) {
      var key = '_' + i;
      obj.key = v;
  });
});
olekhy
  • 15
  • 6
  • This also sets each key of the object to be the index of the array. In my question I asked for the key and value of the object to be the value of the array which i loop through – Andrew Kilburn Dec 10 '15 at 16:25