Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Object Key with jquery.each() loop

I'm creating a namespace in javascript to loop through a form and create an object. The goal of the function when called is to loop through all of a certain form type and construct an object that has a key which is the html input's name and the value as its current value. However, it keeps returning undefined.

Any help would be greatly appreciated:

get_form_data.radio = function(container) { //will return the value 
    var data = {}; //function data object to return
    container.find('input[type="radio"]:checked').each(function() {

        var current_object = {}; //loop temporary object
        var current = $(this); //current element
        var current_key = current.attr('name'); //property category
        var current_value = current.attr('value'); //value to update the database with
        current_object[current_key] = current_value; //temporary object
        console.log(current_object.length); //RETURNS UNDEFINED
        $.extend(data, current_object);

    });

    console.log(data.length); //returns undefined
    return data;
}​
like image 676
JonMorehouse Avatar asked Jul 26 '12 19:07

JonMorehouse


2 Answers

You want to get the var current_object = {}; declaration out of the .each() call. Each iteration of the .each() function redeclares it, and effectively erases it. And forget about $.extend() as well.

var data = {};
container.find('input[type="radio"]:checked').each(function() {
    data[this.name] = this.value;
});
return data;

Untested though from a quick skim of your current code.

like image 83
Richard Neil Ilagan Avatar answered Sep 27 '22 23:09

Richard Neil Ilagan


You need specify key and index value, something like thtat:

array.each(function(index, value) { 
  alert(index + ': ' + value); 
});

In your case:

get_form_data.radio = function(container) { //will return the value 
    var data = {}; //function data object to return
    container.find('input[type="radio"]:checked').each(function(index,value) {

        var current_object = {}; //loop temporary object
        var current = value; //current element
        var current_key = current.attr('name'); //property category
        var current_value = current.attr('value'); //value to update the database with
        current_object[current_key] = current_value; //temporary object
        console.log(current_object.length); //RETURNS UNDEFINED
        $.extend(data, current_object);

    });

    console.log(data.length); //returns undefined
    return data;
}​
like image 23
levi Avatar answered Sep 27 '22 23:09

levi