簡體   English   中英

如何動態創建嵌套對象?

[英]How to create nested object dynamically?

我需要使用 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- section 鍵值以 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"}
    ];

沒有任意嵌套,因此您不需要遞歸或任何繁重的操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM