Javascript:对象内的数组

时间:2016-08-18 12:44:09

标签: javascript arrays object

我有一个需要字符串模型的ASP.NET API:

[HttpPost]
public ActionResult Add(string model)
{

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

    ...

}

到目前为止,我一直这样做是为了将数据传递给它:

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

var model = JSON.stringify(addModel);

它运作得很好。但现在我需要以这种方式发送数据:

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,
}

如何将MyArray添加到对象中,以便以适当的格式传递给后端?

4 个答案:

答案 0 :(得分:2)

只需将其声明为类似

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

答案 1 :(得分:1)

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

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

您可以直接将它们放入

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

您可以使用

进入数组
addModel.MyArray.push( { "SomeValue" : 1, "AnotherValue": a });
声明addModel