Laurens Swart
Laurens Swart

Reputation: 1249

Convert an array to an "array of associative arrays" in jQuery

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

Answers (2)

Luka Jacobowitz
Luka Jacobowitz

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

bknights
bknights

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

Related Questions