简体   繁体   中英

jQuery: Loop through elements by class and create associative array

I have a variable list of elements and need to get their names and values in pairs (associative array or object).

So far I have the following but how do I create the pairs of name and value for each element?

var names = [];
var values = [];

$('.modalField').each(function() {
    fieldName = $(this).attr('name');
    fieldVal = $(this).val();
    
    names.push(fieldName);
    values.push(fieldVal);
});

Thanks for any help,
Tom

Use bracket notation .

var assoc = {};
$('.modalField').each(function() {
    let fieldName = $(this).attr('name');
    let fieldVal = $(this).val();
    assoc[fieldName] = fieldVal;
});

(Also, you should initialize your variables with let/var/const inside the function so they don't leak into the global scope.)

You say name-value but you seem to want an object

You can do EITHER

 // Object const obj = {}; $('.modalField').each(function() { const fieldName = $(this).attr('name'); const fieldVal = $(this).val(); obj[fieldName] = fieldVal }); console.log(obj) // OR Name-Value pair const arr = $('.modalField').map(function() { return { [$(this).attr('name')]: $(this).val() } }).get() console.log(arr)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input name="a" value="1" class="modalField" /> <input name="b" value="2" class="modalField" /> <input name="c" value="3" class="modalField" /> <input name="d" value="4" class="modalField" />

Something like this?

 var fields = []; $('.modalField').each(function() { var name = $(this).attr('name'); var value = $(this).val(); fields.push({ name, value }); }); console.log(fields);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div> <input class="modalField" name="n1" value="v1" /> <input class="modalField" name="n2" value="v2" /> <input class="modalField" name="n3" value="v3" /> </div>

Output:

[
  {
    "name": "n1",
    "value": "v1"
  },
  {
    "name": "n2",
    "value": "v2"
  },
  {
    "name": "n3",
    "value": "v3"
  }
]

Instead of having name & values array, I would suggest you to create an object.

var obj ={};
$('.modalField').each(function() {
    obj[$(this).attr('name')] = $(this).val();
   
});

So this way you will have your object like this (names used as example only): {"name1":"val1","name2":"val2","name3":"val3"}

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