我有这个JS对象:
{
"data": {
"nid": [{
"cid": "32",
"uid": "780",
"comment": "text"
}]
},
"request_status": "found"
}
如何循环浏览这些项目以获得评论价值(“评论”:“文字”)?
答案 0 :(得分:3)
你真的不需要循环来获取它。只是做...
var obj = {"data":{"nid":[{"cid":"32","uid":"780","comment":"text"}]},"request_status":"found"};
var text = obj.data.nid[0].comment;
如果有多个,您可以使用forEach
...
obj.data.nid.forEach(function(val,i) {
alert( val.comment );
});
或传统的for
循环......
for( var i = 0; i < obj.data.nid.length; i++ ) {
alert( obj.data.nid[i].comment );
}
或者如果您想构建一个数组,请使用map
...
var arr = obj.data.nid.map(function(val,i) {
return val.comment;
});
或者再次传统的for
循环...
var arr = []
for( var i = 0; i < obj.data.nid.length; i++ ) {
arr.push( obj.data.nid[i].comment );
}
答案 1 :(得分:1)
如果您只是引用该特定对象(或者您正在使用的每个对象都遵循相同的模式),那么您可以直接访问该值:
var theObj = {"data":{"nid":[{"cid":"32","uid":"780","comment":"text"}]},"request_status":"found"};
alert(theObj.data.nid[0].comment);
如果你想做一些迭代的事情,那么也许试试这个:
var theObj = {"data":{"nid":[{"cid":"32","uid":"780","comment":"text"}]},"request_status":"found"};
for (var index = 0; index < theObj.data.nid.length; index++) {
var item = theObj.data.nid[index];
if (item.comment) {
alert(item.comment);
}
}
或者,如果您真的想要迭代地执行整个事情:
window.searchObj = function(theObj) {
if (theObj.comment) {
alert(theObj.comment);
}
if (theObj instanceof Array) {
searchArray (theObj);
}
else if (theObj instanceof Object) {
for (var key in theObj) {
searchObj(theObj[key]);
}
}
};
window.searchArray = function(theArray) {
for (var index = 0; index < theArray.length; index++) {
var item = theArray[index];
searchObj(item);
}
};
var theObj = {"data":{"nid":[{"cid":"32","uid":"780","comment":"text"}]},"request_status":"found"};
searchObj(theObj);
答案 2 :(得分:1)
假设:
var obj = {
"data": {
"nid": [{
"cid": "32",
"uid": "780",
"comment": "text"
}]
},
"request_status": "found"
};
检索评论的直接方法是:
obj["data"]["nid"][0]["comment"]
// or
obj.data.nid[0].comment
至于“循环”项目以获取值,我不确定循环是否有意义。你是说你可能不知道对象的结构但你知道它会在那里有一个“注释”字段吗?
“nid”数组中只有一个项目 - 如果这只是一个示例,但实际上你将拥有一个包含更多值的数组,你可以遍历该数组:
var nid = obj["data"]["nid"], // get a direct reference to the array to save
i; // repeating obj.data.nid everywhere
for (i=0; i < nid.length; i++) {
// do something with the comment in the current item
console.log(nid[i]["comment"]);
}