简体   繁体   中英

javascript dynamic array creation with key value pairs

I am trying to create dynamic array while selecting values from various select boxes. So I want the created array's key and value should be the value and text of as selected.

for example below are three select boxes for Name, grade and age.

 Name           grade       age
---------      ---------   ---------
 Jack            A          12
 Sam             B          13
 Jessy           A          11

I tried the below code:

   <script>
    var data = [];
    $('.filter_select').change(function() {
        data[$(this).attr('name')] = $(this).val();   
    });
    </script>

But I am not able to iterate the created array for using $.each(data, function() {});

Whenever I do selecting any of the three select boxes the array should be look like this and can be iterated using $.each

var data = []
data['Name'] = 'Sam'
data['grade'] = 'A'
data['age'] = '12'    

Any help could lead right way.

Use var data = {}; if you only need key/value pairs and don't need array capabilities. Iterating properties could be done like this:

for (var property in data) {
    // your code accessing data[property]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM