有没有办法将json对象的“路径”保存到变量?也就是说,如果我有这样的事情:
var obj = {"Mattress": {
"productDelivered": "Arranged by Retailer",
"productAge": {
"year": "0",
"month": "6"
}
}
};
如何循环并将每个关键节点名称保存到变量?例如。 (我需要这种格式):床垫[productDelivered],床垫[productAge] [年],床垫[productAge] [月]
我已经部分地在这个小提琴中http://jsfiddle.net/4cEwf/,但正如你在日志中看到的那样,年份和月份不会分开,而是附加到数组中。我知道这是因为我已经进行了循环,但我仍然坚持如何进步以获得我需要的数据格式。我在小提琴中设置的流程正在模仿我需要的东西。
我有没有考虑过这样做?
答案 0 :(得分:1)
尝试
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)
演示:Fiddle
答案 1 :(得分: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]);
}
}