0

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>

5
  • What isn’t working? It seems to work fine. Why did you use an object ({}) instead of an array ([]) for assarray? You can do the same thing without jQuery: stringarray.map(function(a){return {"variable": a};}). Commented Apr 14, 2016 at 19:51
  • Non-jQuery ES6: var out = arr.map(el => ({ variable: el }))... Commented Apr 14, 2016 at 19:53
  • But, yeah, var assarray= {} needs to be var assarray= [] as answered below. Commented Apr 14, 2016 at 19:54
  • Just change assarray={} to assarray=[] to get your wish Commented Apr 14, 2016 at 19:54
  • Yeah, that was my mistake. There were so many things going wrong that I got kindof desperate. I had assarray=[]; first but probably had something else mixed up at that time... Thanks guys. Commented Apr 14, 2016 at 22:06

2 Answers 2

3

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};});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Managed to get it working. Turns out however that the array I was trying to parse has over 100.000 entries which just gave me a BSOD, LOL! Guess I'll have to find another solution... :-P
1

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.

2 Comments

Well he already has jQuery so unless he already knows IE8 and lower are out of the picture then using jQuery is less work.
Not necessarily disagreeing with you here, but I feel the non-jquery version is generally more elegant and should be used whereever you can :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.