Convert a table to a set & ldquo; array of associative arrays & rdquo; in jQuery

advertisements

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>

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};});