Glenn Utter Glenn Utter - 3 months ago 9
Javascript Question

Javascript: Array inside object

I have a ASP.NET API that expects a string model:

[HttpPost]
public ActionResult Add(string model)
{

var m = JsonConvert.DeserializeObject<CustomModel>(model);

...

}


So far, I have been doing this to pass data to it:

var addModel = {
"SomeValue": {
"Some": "example",
"Value": "example"
},
"AnotherValue": "example"
}

var model = JSON.stringify(addModel);


And it works just fine. But now I need to ship data this way:

var addModel = {
"SomeValue": {
"Some": "example",
"Value": "example"
},
"AnotherValue": "example",

"MyArray[0].SomeValue": 1,
"MyArray[0].AnotherValue": a,
"MyArray[1].SomeValue": 1,
"MyArray[1].AnotherValue": a,
}


How do I add
MyArray
to the object so it can be passed to the back-end in the proper format?

Answer

You can put them in directly with

addModel.MyArray[0] = { "SomeValue" : 1, "AnotherValue": a };

You can push into the array with

addModel.MyArray.push( { "SomeValue" : 1, "AnotherValue": a });

after addModel is declared