Martin Naude
Martin Naude

Reputation: 23

Converting String variable to array

I have created method that take certain data from an array, and creates a new dictionary with the array by adding in some pre-defined strings,

Im able to create the new array's I need, but I seem to be storing it as a String variable instead of as an array. Here is my Code:

var createContestantsDropdownlist = ContestantInfoDropdown();

function ContestantInfoDropdown() {
var ContestantTest = ['Contestant 1', 'Contestant 2', 'Contestant 3', 'Contestant 4'];  
var option = [];
    for (var i=0;i<ContestantTest.length;i++){
    option += '{value: \'' + ContestantTest[i] + '\'},';
    }
    option += '{value: \'Contestant 5\'}';
    return option
  };

When I take a look at the data that has been created, it's all in the correct format, but I need to try and remove the double quotes at the beginning and end to make it an array, and not a string value. See here how the string value Looks.

All I would like to know is how to convert this from a string by simply removing the Double quotes at the beginning and the end, or am I completely on the wrong track here. any help appreciated!

Thanks!

Upvotes: 0

Views: 303

Answers (4)

Josh
Josh

Reputation: 4816

var createContestantsDropdownlist = ContestantInfoDropdown

function ContestantInfoDropdown()
{
    var ContestantTest = ['Contestant 1', 'Contestant 2', 'Contestant 3', 'Contestant 4']
    var option = ContestantTest.map(function(x) { return { value: x } })
    option.push ({value: 'Contestant 5'})
    return option
}

Upvotes: 0

John Boker
John Boker

Reputation: 83729

Instead of concatenating a string you should push the values onto the array like:

function ContestantInfoDropdown() {
  var ContestantTest = ['Contestant 1', 'Contestant 2', 'Contestant 3', 'Contestant 4'];  
  var option = [];
      for (var i=0;i<ContestantTest.length;i++){
          option.push({value: ContestantTest[i] });
      }
      option.push({value: 'Contestant 5' });
      return option
};

var createContestantsDropdownlist = ContestantInfoDropdown();

console.log(createContestantsDropdownlist);

example fiddle https://jsfiddle.net/c9j1hure/

Upvotes: 0

Filipe Borges
Filipe Borges

Reputation: 2793

using += on options variable cast it to a string. Use options.push(ContestantTest[i]) instead.

Upvotes: 0

mhodges
mhodges

Reputation: 11136

Try this:

option.push({value: ContestantTest[i]});

That will actually push the object onto the array rather than build out a string like you are now.

Upvotes: 2

Related Questions