RJP
RJP

Reputation: 4116

How to build a json object with a loop?

I'm trying to loop through a number of items, and create a json object. Each loop should be a new item on the object, but I'm having some issues doing it. It seems that only one set of items gets added, instead of multiple ones.

Here is my code:

jsonObj = {}
rows.each(function (index) {
    jsonObj["id"] = $this.find('.elementOne').val();
    jsonObj["name"] = $this.find('.elementTwo').text();

});

Here is what my json looks like:

{
    id: "3"
    name: "Stuff"
},

Here is what I am trying to do:

{
    id: "1"
    name: "Stuff"
},
{
    id: "2"
    name: "Stuff"
},
{
    id: "3"
    name: "Stuff"
}

Upvotes: 8

Views: 44323

Answers (6)

Atanas Kovachev
Atanas Kovachev

Reputation: 431

You can do it like this with jquery. The function will expect form elements of type input. It will iterate over thr passed form and it will collect each input name and value and it will create a json object like

Exmple:

HTML

<form action="" method="post" id="myForm">
    <input type="text" name="field1" value="I am value of field 1"/>
    <input type="text" name="field2" value="I am value of field 2"/>
</form>

Javascript

function buildObject(form) {
            var jsonObject = [],
                tempObj = {};
            $(form).find("input:not(input[type='submit'])").each(function() {
                tempObj[$(this).attr("name")] = $(this).val();
            });

            jsonObject.push(tempObj);

            return jsonObject[0];
    }
    buildObject($("#myForm"));
    //Will produce

     jsonObj = {
        field1 : "I am value of field 1",
        field2 : "I am value of field 2"    
    }

Upvotes: 3

Anurag
Anurag

Reputation: 141869

What you want is an array of objects. When you try to write the same property on the same object multiple times, it gets overwritten which is why you're seeing id and name contain values for the last iteration of the loop.

Although you haven't tagged the question with jQuery, it does look like jQuery, so here's a solution:

I've taken the liberty to change $this to this because $this seems to be referring to the same object in each iteration, which is now what you may want (methinks)

var myArray = rows.map(function() {
    return {
        id: $(this).find('.elementOne').val(),
        name: $(this).find('.elementTwo').text()
    };
});

Upvotes: 4

Mitya
Mitya

Reputation: 34556

This is because you're merely overwriting the same properties of your object, id and name, each time. You need to be making a sub-object for each, then push it into the master object (which I've converted to array, since it's non-associative).

var jsonObj = []
rows.each(function (index) {
    var temp_obj = {};
    temp_obj["id"] = $this.find('.elementOne').val();
    temp_obj["name"] = $this.find('.elementTwo').text();
    jsonObj.push(temp_obj);
});

[EDIT] - as Mark Eirich's answer shows, the temp_obj is unnecessary - you could push an anonymous object instead, but I defined temp_obj just to make it crystal clear what's happening.

Also read Quentin's very good points re: common confusion between JavaScript objects and JSON.

Upvotes: 2

Quentin
Quentin

Reputation: 943214

There is no JSON here. Please don't confuse:

  • A JavaScript object (a data structure)
  • A JavaScript object literal (code to create such a data structure)
  • JSON (a data format based on a subset of object literal notation)

If you want an ordered list of objects (or any other kind of JavaScript data structure) then use an array. Arrays have a push method.

var myData = [];
rows.each(function (index) {
    var obj = { 
        id: $this.find('.elementOne').val(),
        name: $this.find('.elementTwo').text()
    };
    myData.push(obj);
});

Upvotes: 28

gdoron
gdoron

Reputation: 150253

You override the object instead of adding it a new value each iteration.

Fixed code using an array:

jsonObj = [];
rows.each(function(index) {
    jsonObj.push({
        'id': $this.find('.elementOne').val(),
        'name': $this.find('.elementTwo').text()
    });
});​

Upvotes: 5

Mark Eirich
Mark Eirich

Reputation: 10114

var jsonObj = [];
rows.each(function(index) {
    jsonObj.push({
        id: $this.find('.elementOne').val(),
        name: $this.find('.elementTwo').text()
    });
});

Upvotes: 1

Related Questions