Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
}
like image 889
RJP Avatar asked Jun 30 '12 22:06

RJP


People also ask

Can you do loops in JSON?

Looping Using JSON It's a light format for storing and transferring data from one place to another. So in looping, it is one of the most commonly used techniques for transporting data that is the array format or in attribute values. Here's an example that demonstrates the above concept.

How do I iterate through a JSON object?

Use Object.values() or Object. entries(). These will return an array which we can then iterate over. Note that the const [key, value] = entry; syntax is an example of array destructuring that was introduced to the language in ES2015.

Can you have Booleans in JSON?

JSON BooleansValues in JSON can be true/false.

Can JSON be hacked?

In the case of JSON hijacking, the attacker aims to intercept JSON data sent to the web application from the web server. The attacker creates a malicious website and embeds a script tag in its code that attempts to access JSON data from the attacked web application.


1 Answers

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);
});
like image 60
Quentin Avatar answered Oct 22 '22 05:10

Quentin