Glenn Utter
Glenn Utter

Reputation: 2363

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?

Upvotes: 0

Views: 2054

Answers (4)

black_pottery_beauty
black_pottery_beauty

Reputation: 879

var myArray = [
    {
        "a":1,
        "b":2
    },
    {
        "a":1,
        "b":2
    }
];

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

Upvotes: 0

Mark Schultheiss
Mark Schultheiss

Reputation: 34158

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

Upvotes: 0

adam-beck
adam-beck

Reputation: 6009

"MyArray": [
 {
    "SomeValue": 1,
    "AnotherValue": a
 },
 {
    "SomeValue": 1,
    "AnotherValue": a
}
]

Upvotes: 1

deadwards
deadwards

Reputation: 2118

Just declare it as an array like so

var addModel = {
    "SomeValue": {
        "Some": "example",
        "Value": "example"
    },
    "AnotherValue": "example",    
    "MyArray": [
        { "SomeValue" : 1, "AnotherValue": a },
        { "SomeValue" : 1, "AnotherValue": a }
    ]
}

Upvotes: 2

Related Questions