Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
102
rated 0 times [  106] [ 4]  / answers: 1 / hits: 42739  / 12 Years ago, sat, june 30, 2012, 12:00:00

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
}

More From » jquery

 Answers
5

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);
});

[#84552] Friday, June 29, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
emerald

Total Points: 547
Total Questions: 96
Total Answers: 122

Location: Oman
Member since Fri, Dec 23, 2022
1 Year ago
;