How to convert an array to associative? I write the following:

arr=[one,two,three] res=[] $.each(arr,function(idx,el){ idx+=1 res.push(idx,el) }) 

should be like this [1:one,2:two,3:three] and I have [1,one,2,two,3,three]

  • what result is expected and how then is it planned to use it? Well, judging by the code, you just need to unshift for an unshift element and the indexes will align - Grundy
  • How will the result be used later? Do you want to just move the indexes? - Grundy
  • an associative array in JS is an object, so in your case the associative array looks like this: {1: one, 2: two, 3: three} - MasterAlex
  • one
    @MasterAlex, object is not an array :) - Grundy
  • 2
    @MasterAlex, yeah, they have problems with terminology :) - Grundy

1 answer 1

Your code simply inserts several elements into the array. To get [{1: one}, {2: two}, {3: three}] you need to insert already prepared objects:

 arr=['one','two','three']; var res=[]; $.each(arr,function(idx,el) { var item = {}; item[idx+1] = el; res.push(item); }) 

It is much more convenient to use not an array with objects, but an object with index properties

 { 1: one, 2: two, 3: three, } 

To get such an object, you need to use the following code:

 var arr= ['one', 'two', 'three']; var res = {}; $.each(arr,function(idx,el){ res[idx+1] = el; }) 
  • one
    @ D-side, most likely a typo with copy-paste not fixed - Grundy