是否可以将JSON的遍历路径存储在一级以上的变量中?
在变量中定义JSON遍历路径。
var jsonPathLink = 'sequenceId';
var jsonPathText = 'answer.body';
jQuery AJAX 调用。 (我删除了所有不必要的设置,但如果您想要包含更多代码,请告诉我。)
$.ajax({
success: function(data){
if(data.length > 0){
for(x in data){
console.log(data[x][jsonPathLink]); // This works.
console.log(data[x][jsonPathText]); // This does not work.
console.log(data[x] + jsonPathText); // This also does not work.
}
}
}
});
最佳答案
你可以像下面这样写一个 traverseObject 函数:
function traverseObj(obj, path) {
var arr = path.split('.'),
len = arr.length,
i = 0,
ret;
for ( ; i<len; i+=1 ) {
// on the first iteration, the passed object
// is cached in the ret-variable.
ret = !i
? obj[arr[i]]
: ret[arr[i]];
}
return ret;
}
路径的单个元素通过遍历它们来应用于传递的对象。结果被缓存并返回。
关于javascript - 使用字符串从 jQuery AJAX 遍历 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11195648/