如何动态创建嵌套对象?

时间:2016-05-05 20:27:58

标签: javascript json

我需要使用JavaScript创建这种格式的对象。

var results = {
    "A-1": [
        { "object": "daily", "type": "when", "field": "Period" }
    ],
    "A-2": [
        { "object": "weekly", "type": "when", "field": "Period" }
    ],
    "A-3": [
        { "object": "monthly", "type": "when", "field": "Period" }
    ],
    "B-1": [
        { "object": "Boston", "type": "who", "field": "City" },
        { "object": "AG", "type": "what", "field": "region" },
        { "object": "L1", "type": "where", "field": "Level" }
    ],
    "B-2": [
        { "object": "New York", "type": "who", "field": "City" },
        { "object": "AG", "type": "what", "field": "region" },
        { "object": "L2", "type": "where", "field": "Level" }
    ],
    "B-3": [
        { "object": "Paris", "type": "who", "field": "City" },
        { "object": "EURO", "type": "what", "field": "region" },
        { "object": "L1", "type": "where", "field": "Level" }
    ],
    "B-4": [
        { "object": "Boston", "type": "who", "field": "City" },
        { "object": "AG", "type": "what", "field": "region" },
        { "object": "L2", "type": "where", "field": "Level" }
    ]
};

var periodList = "daily,weekly,monthly";

{J}格式的Web服务返回B-部分键值,如下所示:

 [
    { "object": "Boston", "level": "L1", "region": "AG" },
    { "object": "Paris", "level": "L1", "region": "EURO" },
    { "object": "Boston", "level": "L2", "region": "AG" },
    { "object": "China", "level": "L1", "region": "AP" },
    { "object": "New York", "level": "L2", "region": "AG" }
]

每个B-对象都包含城市,区域和级别数组。

请帮助如何动态创建此结构?

1 个答案:

答案 0 :(得分:2)

只需使用两个简单的循环:

var results = {};
var periods = periodList.split(",");
for (var i=0; i<periods.length; i++)
    results["A-"+(i+1)] = [
        {"object": periods[i],    "type": "when",   "field": "Period"}
    ];
for (var i=0; i<json.length; i++)
    results["B-"+(i+1)] = [
        {"object": json[i].object, "type": "who",   "field": "City"},
        {"object": json[i].region, "type": "what",  "field": "region"},
        {"object": json[i].level,  "type": "where", "field": "Level"}
    ];

没有任意嵌套,所以你不需要递归或任何沉重的东西。