Adding a list of data to object inside loop

45 views Asked by At

I have been attempting to add a list of values into a object/associative array so i can get a list of values from the input of a multiselect plugin. Im wanting to add the name of the input as the object key.

Problem: Doesnt seem to create a list, just updates the last input value in loop...what am i doing wrong here?

var selectObj = {}; 

$('input').each(function(inputKey)
{
    alert($(this).val());   //all input values shown
    selectObj[$(this).attr('name')] = $(this).val(); 
 });

alert(JSON.stringify(selectObj));    //last input value shown

Desired Results:

  • (1 multi-select):

selectObj={"listName1":"12,3,31,4"}

  • (2 multi-select):

selectObj={"listName1":"12,3,31,4"},{"listName2":"1,32,43,5"}

2

There are 2 answers

0
Orbitall On BEST ANSWER

Thanks to gillesc for helping me solve this, it now successfully checks for all the input that has been checked or selected by various multi select plugins and outputs to the inputValues object:

$('input').each(function()
{
    if($(this).closest('li').hasClass("checked") || $(this).closest('li').hasClass("active"))
    {                 
        var selectKey = $(this).attr('name');                  
        if (!inputValues[selectKey]) 
        { 
            inputValues[selectKey] = [];
        } 
        inputValues[selectKey].push($(this).val());
    }
}
3
Abhinav On

This is what you can do based on your edits of desired results

var selectObj = {}; 
var inputValues = [];
$('input').each(function(inputKey){
  attrName = $(this).attr('name');
  inputValues.push(value);

});
 selectObj[attrName] = inputValues .toString();