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

1 Answer 1

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));
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.