Sunday 26 March 2017

javascript - Create multidimensional array from string











I want to create an options array from a string. How can i create an array as



{
width : 100,

height : 200
}


from a string like



'width=100&height=200'


Is there to create such arrays?



Answer



That's not an array, it's an object. It's not multidimensional either.



But anyway, you can split the string on the & separator and then split each item on the =:



var input = 'width=100&height=200',
output = {},
working = input.split("&"),
current,
i;


for (i=0; i < working.length; i++){
current = working[i].split("=");
output[current[0]] = current[1];
}

// output is now the object you described.


Of course this doesn't validate the input string, and doesn't cater for when the same property appears more than once (you might like to create an array of values in that case), but it should get you started. It would be nice to encapsulate the above in a function, but that I leave as an exercise for the reader...



No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...