Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically build JSON object list from Javascript [duplicate]

I'm trying to end up with the below JSON from an HTML form.

{
    "Name":"Curtis",
    "Phone":"555-555-5555",
    "Replacements":
    [
        {
            "Company":"ABC Company",
            "Amount":100
        },
        {
            "Company":"123 Company",
            "Amount":200
        },
    ]
}

I'm struggling with the JavaScript in regards to building the array for the replacements.

var o = {};
o["Name"] = $("#Name").val();
o["Phone"] = $("#Phone").val();

//How do I append the dynamic list of replacements here?
//$("#Company1").val();
//$("#Amount1").val();
//$("#Company2").val();
//$("#Amount2").val();

$("#txtJSON").val(JSON.stringify(o));
like image 559
Curtis Avatar asked Jan 24 '26 00:01

Curtis


1 Answers

Create Replacements property array and push objects in it:

var o = {};
o.Name. = $("#Name").val();
o.Phone = $("#Phone").val();

o.Replacements = [];

o.Replacements.push({
    Company: $("#Company1").val(),
    Amount:  $("#Amount1").val()
}, {
    Company: $("#Company2").val(),
    Amount:  $("#Amount2").val()
});

$("#txtJSON").val(JSON.stringify(o));
like image 195
dfsq Avatar answered Jan 26 '26 13:01

dfsq