2012-01-15 56 views
1

我有這樣的JS對象:循環中的JS對象

{ 
    "data": { 
     "nid": [{ 
      "cid": "32", 
      "uid": "780", 
      "comment": "text" 
     }] 
    }, 
    "request_status": "found" 
} 

我怎麼能循環通過這些項目來獲得評論值(「評論」:「文本」)?

+1

爲什麼你要循環呢?你可以直接用'object.data.nid [0] .comment' – JohnP 2012-01-15 07:38:39

回答

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); 
} 
+0

這樣的東西來得到它,但是如果nid更改爲數字? { 「數據」:{ 「1222」:[{ 「CID」: 「32」, 「UID」: 「780」, 「評論」: 「文本」 }] }, 「 request_status「:」found「 } – Laky 2012-01-15 08:00:24

+1

@Laky:然後將'obj.data.nid'改爲'obj.data [1222]'。還是你說它可能是一個不同的數字,或一組數字? – 2012-01-15 08:05:31

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); 
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"]); 
}