1

鉴于以下情况:

var a = JSON.parse('{"fst":"data1","snd":{"ind2":"data2"}}');
var index = "fst";
var res = a[index]; //res = data1
var index2 = "????";
var res2 = a[index2]; //res = data2

我应该穿什么index2这样res2等于data2

我正在寻找一种通用语法,它可以让我在解析的 json 的任何级别上抓取一个元素,只需修改索引字符串。

(我正在循环遍历来自 json 派生对象的不同位置/级别的元素列表以构建表)

任何帮助将非常感激

4

3 回答 3

2

您正在访问属性的属性,语法反映了这一点:

var res = a['snd']['ind2'];

没有办法直接直接抓取“嵌套”的属性。如果您被允许更改原始对象,您可以为每个对象添加快捷方式访问器:

//Credit goes to Esailja for the original
function deepAccess(obj) {
    function nestedAccess(o, level) {
        if (typeof o == "object") {
            var level = level || "";
            for (p in o) {
                if (o.hasOwnProperty(p)) {
                    if (level && typeof(o[p]) != "object") {
                        obj[level + "." + p] = o[p];
                    }
                    nestedAccess(o[p], (level ? level + "." : "") + p);
                }
            }
        }
    }
    nestedAccess(obj);
}

deepAccess(a);

a["snd.ind2"];
于 2012-11-23T18:21:51.673 回答
2

你需要一个功能

function deepAccess( obj, str ) {
    var parts = str.split("."),
        cur = obj;
    for( var i = 0; i < parts.length; ++i ) {
        cur = cur[parts[i]];    
    }

    return cur;
}

var index = "fst";
deepAccess( a, index ); //"data1"
index = "snd.ind2";
deepAccess( a, index ); //"data2"
于 2012-11-23T18:25:27.260 回答
1
var someObject1 = {};
var someObject2 = {e01: '*', e02: {e03: '*', e04: '*'}, e05: '*'};
var someObject3 = {e01: {e02: {e03: '*'}}};

function setValueByPath(obj, path, value) {
    var pathArray = path.split('.');

    function goDownstears(o, chunk, val) {
        var prop = chunk.shift();

        if(!o.hasOwnProperty(prop)) o[prop] = {};

        o[prop] = (chunk.length > 0) ? goDownstears(o[prop], chunk, val) : val;

        return o;
    }

    obj = goDownstears(obj, pathArray, value);
}

setValueByPath(someObject1, 'e01.e02.e03', 'changed');

setValueByPath(someObject2, 'e02.e04', 'changed');

setValueByPath(someObject3, 'e01.e02.e03', 'changed');
setValueByPath(someObject3, 'e01.e02.e04', 'changed');
setValueByPath(someObject3, 'e02.e01.e01', 'changed');

console.log(someObject1);
console.log(someObject2);
console.log(someObject3);

我的问题在这里关闭了设置一个对象属性,如 obj['level1.level2.leve3'] = value

见这里http://jsfiddle.net/zafod/RDGwY

此问题用于设置值,但您可以通过迭代返回询问的属性

于 2012-11-26T15:39:59.660 回答