如何动态创建嵌套对象

How to create nested object dynamically?

本文关键字:创建 嵌套 对象 动态 何动态      更新时间:2023-09-26

我需要使用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";

B-部分键值以JSON格式从web服务返回,如下所示:

 [
    { "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-对象都包含城市、地区和级别数组。

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

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

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"}
    ];

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