1

有没有办法将 json 对象的“路径”保存到变量中?也就是说,如果我有这样的事情:

var obj = {"Mattress": {
                    "productDelivered": "Arranged by Retailer",
                    "productAge": {
                                "year": "0",
                                "month": "6"
                                }
                    }
       };

如何循环遍历每个关键节点名称并将其保存到变量中?例如。(我需要这种格式):Mattress[productDelivered], Mattress[productAge][year], Mattress[productAge][month]

我在这个小提琴http://jsfiddle.net/4cEwf/中有部分内容,但正如您在日志中看到的那样,年份和月份不会分开,但也会附加到数组中。我知道这是因为我正在进行循环,但我一直坚持如何获得所需的数据格式。我在小提琴中设置的流程正在模拟我所需要的。

有没有我没有考虑过的方法?

4

2 回答 2

2

尝试

var obj = {
    "Mattress": {
        "productDelivered": "Arranged by Retailer",
        "productAge": {
            "year": "0",
            "month": "6"
        }
    }
};

var array = [];

function process(obj, array, current){
    var ikey, value;
    for(key in obj){
        if(obj.hasOwnProperty(key)){
            value = obj[key];
            ikey = current ? current + '[' + key + ']' : key;
            if(typeof value == 'object'){
                process(value, array, ikey)
            } else {
                array.push(ikey)
            }
        }
    }
}
process(obj, array, '');
console.log(array)

演示:小提琴

于 2013-07-24T06:16:02.217 回答
0
var obj = {"Mattress": {
                    "productDelivered": "Arranged by Retailer",
                    "productAge": {
                                "year": "0",
                                "month": "6"
                                }
                    }
       };
var Mattress = new Array();
for(var i in obj.Mattress){
    if(typeof(obj.Mattress[i])==='object'){
        for(var j in obj.Mattress[i]){
            if(Mattress[i]!=undefined){
                Mattress[i][j] = obj.Mattress[i][j];
            }
            else{
                Mattress[i] = new Array();
                Mattress[i][j] = obj.Mattress[i][j];
            }
        }
    }
    else{
        Mattress[i] = obj.Mattress[i];
    }
}     
for(var i in Mattress){
    if(typeof(Mattress[i])==='object'){
        for(var j in Mattress[i]){
            alert(j+":"+Mattress[i][j]);
        }
    }
    else{
        alert(i+":"+Mattress[i]);
    }
}
于 2013-07-24T06:33:40.730 回答