Reputation: 1249
I'm trying to do another silly thing in jQuery...
I have a bunch of strings in an array:
[ var1 , var2 , var3 , var4 , var5 , var6 , var7 , ...]
And I want the array to become an "array of associative arrays", with the same index every time... (don't ask me why xD):
[ { 'variable' : var1 } , { 'variable' : var2 } , { 'variable' : var3 } , ... ]
The index 'variable' is the same every time.
How does one do this? My attempt (below) isn't working...
var stringarray = ['var1', 'var2', 'var3', 'var4'];
var assarray = {};
$.each(stringarray, function(index, value) {
assarray[index] = {
'variable': value
};
});
document.write(JSON.stringify(assarray))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 0
Views: 1853
Reputation: 23512
Yeah, definitely use map
. But I'd just use use the built-in since ES5:
var assarray = stringarray.map(function(element){
return { variable: element };
});
Check out the docs here. Should work on every browser since IE9.
Upvotes: 1
Reputation: 15402
Basically because assarray is not an array. It needs to be:
var assarray = [];
Also you could do:
var assarray = $.map(stringarray, function(val){ return {variable:val};});
Upvotes: 3