这可能做到吗,或者我该怎么做?

arrayElement = new Object();
JSONkey = jsonData.table[0].key; // key in table[0] is "ident/Lesson/Value"
JSONkey = JSONkey.replace(/\//g, '.'); // now JSONkey is "ident.Lesson.Value"

arrayElement.JSONkey = "value1" // Can I do this or how would I?


因此arrayElement.JSONkeyarrayElement.ident.Lesson.Value相同

最佳答案

arrayElement = new Object();
JSONkey = jsonData.table[0].key; // key in table[0] is "ident/Lesson/Value"
JSONkey = JSONkey.replace(/\//g, '.'); // now JSONkey is "ident.Lesson.Value"

deepRef(arrayElement, JSONkey, "value1");

function deepRef(ref, key, value) {
    var segments = key.split("."),
        n = segments.length;
    for (var i=0, skey; i<n; i++) {
        skey = segments[i];
        if (i < n - 1) {
            ref[skey] = {};
            ref = ref[skey];
        } else {
            ref[skey] = value;
        }
    }
}

09-25 20:59