如何在纯JavaScript中动态构建数据结构?

时间:2018-01-21 17:49:36

标签: javascript

是否有任何插件允许在纯JavaScript对象或JSON中动态构建以下数据结构?

这是我想要实现的结构:

检查我的plunker(https://plnkr.co/edit/1eWjXLPumuOMhv8BjaNw?p=preview

{
    "name": "Select0",
    "id": "select0",
    "values": [
        "Option1",
        "Option2"
    ],
    "dependent": {
        "name": "Select1",
        "id": "select1",
        "values": {
            "Option1": [
                "Option11",
                "Option12"
            ],
            "Option2": [
                "Option21",
                "Option22"
            ]
        },
        "dependent": {
            "name": "Select2",
            "id": "select2",
            "values": {
                "Option1": {
                    "Option11": [
                        "Option111",
                        "Option112"
                    ],
                    "Option12": [
                        "Option121",
                        "Option122"
                    ]
                },
                "Option2": {
                    "Option21": [
                        "Option211",
                        "Option212"
                    ],
                    "Option22": [
                        "Option221",
                        "Option222"
                    ]
                }
            },
            "dependent": []
        }
    }
}

1 个答案:

答案 0 :(得分:0)

请注意,您可以在对象的属性上设置值,然后将其作为JSON打印。

var obj = {};
object.name = "Select0";
// Set more properities.
// Stringify object to JSON format looking as the one in the question.
var json = JSON.stringify(obj, null, 2);
// Verify by printing on the screen.
console.log(json);