keewee279
keewee279

Reputation: 1654

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

Upvotes: 0

Views: 3094

Answers (4)

mplungjan
mplungjan

Reputation: 178285

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" />

Upvotes: 0

I wrestled a bear once.
I wrestled a bear once.

Reputation: 23379

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.)

Upvotes: 1

VarunPrashar
VarunPrashar

Reputation: 34

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"}

Upvotes: 0

Shadab
Shadab

Reputation: 1347

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"
  }
]

Upvotes: 0

Related Questions