简体   繁体   中英

Creating a JSON object in JavaScript dynamically

I need to create a JSON object dynamically in JavaScript using a for loop. I have tried using the array.Push method but it is not working. I am only getting the first value getting stored. The remaining values of the iteration are not getting stored.

This is what I am trying:

var array = [];
    for (var i = 0; i < 4; i++) {
        var username = drlist.reportees[i].name;
        var think40 = getthink40(n,m);
        if (think40.isSuccessful){
            var result = think40.array;
            var length = result.length;
            var tes= 0;
            for (var j = 0; j < length-1; j++){
                tes = tes + parseFloat(result[j].duration);
            }
            var hours = tes/60;
            var think = (hours/40)*100;
            if (think > 100)
                {
                think =100;
                }
            array.push( {
                    name: username,
                    hours: think
                });
                }
        return array;
    }

Try this...

var jsonArray = [];
function test (){
for (var i=0; i<3;i++)
{
   var jsonObject = {'a':1, 'b':2}; jsonArray.push(jsonObject);
}
return jsonArray;
}

Note : You are returning the jsonObject instead of jsonArray. You should probably return the jsonArray.

Creating and manipulating a JSON object in JavaScript is not very different from any other type of object, but does have a few limitations. These are primarily around the data types JSON supports and the two most notable are a lack of dates and functions.

JavaScript objects can contain almost anything (increasingly so with ES6 and symbols) but JSON is a limited subset of that. The JSON spec is short and easy to read (complete with pictures!), so I would recommend starting there. As you'll see in the spec, the value types include strings, numbers, objects, array, boolean keywords, and null. There is no support for dates -- easily worked around by formatting them as ISO 8601 strings -- or functions.

To turn a valid JavaScript object into the final JSON form involves a limited amount of string formatting and escaping. Most modern browsers have a global JSON API for doing that, providing both parse and render ( stringify ) methods. This is your codec and the first and final step when manipulating JSON.

In your example, you would build the object as normal, assigning properties ( foo.bar = 3 ) as necessary. At the very end, to return the JSON (which is really just a string in JS), you would take the object you've created and pass it to JSON.stringify . This will produce a valid, safe, escaped JSON string suitable for passing to web services and other scripts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM