Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

This question already has an answer here:

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));
share|improve this question

marked as duplicate by blex, kapa javascript Mar 25 at 8:24

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
You should take a look at this: Convert form data to JS object with jQuery – blex Mar 24 at 20:17

1 Answer 1

up vote 1 down vote accepted

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));
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.