3

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));
Curtis
  • 391
  • 2
  • 6
  • 17
  • You should take a look at this: [Convert form data to JS object with jQuery](http://stackoverflow.com/questions/1184624/convert-form-data-to-js-object-with-jquery) – blex Mar 24 '15 at 20:17
  • Have you check this : https://stackoverflow.com/questions/1184624/convert-form-data-to-javascript-object-with-jquery/39248551#39248551 – Bhavik Hirani Mar 26 '18 at 08:01

1 Answers1

4

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));
dfsq
  • 191,768
  • 25
  • 236
  • 258