Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create an associative array in jquery

This is what I have so far and the shoe types are boots, wellingtons, leather, trainers (in that order)

I want to iterate through and assign the value so I haves something like

var shoeArray = { boots : '3', wellingtons: '0', leather : '1', trainers: '3'};

at the moment I just get an array of {3,0,1,3} which I can work with but it is not very helpful.

function shoe_types() {
    var shoeArray = [];
    $('[type=number]').each(function(){
        $('span[data-field='+$(this).attr('id')+']').text($(this).val());      
        shoeArray.push ( parseInt($(this).val()) );      
    });             
    return shoeArray;        
}
like image 647
LeBlaireau Avatar asked Nov 05 '13 11:11

LeBlaireau


3 Answers

Check this function

function shoe_types() {
    var shoeArray = {}; // note this
    $('[type=number]').each(function(){
       $('span[data-field='+$(this).attr('id')+']').text($(this).val());
       shoeArray[$(this).attr('id')] =  parseInt($(this).val()) ;
    });
    return shoeArray;

}

PS: Assuming $(this).attr('id') has all the shoe types

like image 138
zzlalani Avatar answered Oct 17 '22 05:10

zzlalani


Associative array in javascript is the same as object

Example:

var a = {};
a["name"] = 12;
a["description"] = "description parameter";
console.log(a); // Object {name: 12, description: "description parameter"}

var b = [];
b["name"] = 12;
b["description"] = "description parameter";
console.log(b); // [name: 12, description: "description parameter"]
like image 37
Mykyta Shyrin Avatar answered Oct 17 '22 06:10

Mykyta Shyrin


What you want is a function that will return an object {}

LIVE DEMO

function shoe_types(){
   var shoeObj = {};
   $('[name="number"]').each(function(){
     shoeObj[this.id] = this.value;
   });
   return shoeObj;
}

shoe_types(); // [object Object]
like image 7
Roko C. Buljan Avatar answered Oct 17 '22 07:10

Roko C. Buljan