鉴于以下内容:
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派生对象的不同位置/级别的元素列表以构建表格)
非常感谢任何帮助
答案 0 :(得分: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"];
答案 1 :(得分: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"
答案 2 :(得分: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);
我的问题已在此处结束set an object property with sugar like obj['level1.level2.leve3'] = value
请参阅此处http://jsfiddle.net/zafod/RDGwY
此问题适用于设置值,但您只需通过迭代返回一个ask属性