create an associative array in jquery

前端 未结 5 1766
迷失自我
迷失自我 2021-01-01 23:43

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 th

相关标签:
5条回答
  • 2021-01-02 00:08

    if $(this).attr('id') is the type of shoes you can try that

    shoeArray[$(this).attr('id')] = parseInt($(this).val());
    
    0 讨论(0)
  • 2021-01-02 00:12

    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

    0 讨论(0)
  • 2021-01-02 00:16

    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"]
    
    0 讨论(0)
  • 2021-01-02 00:20

    You can try this to create an associate array in jquery

    var arr = {};
    $('[type=number]').each(function(){
        arr.push({
             $(this).attr('id'): $(this).val()              
         });
    });
    
    console.log(arr);
    

    This will allow you to send your all data whatever you want to pass in array by ajax.

    0 讨论(0)
  • 2021-01-02 00:34

    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]
    
    0 讨论(0)
提交回复
热议问题