2015-07-10 78 views
0

我正在嘗試從主對象中獲取對象。主對象中的數組包含 這些其他對象,我可以通過調用'oData.events.event[0]'來訪問第一個元素,但是我想循環獲取[1], [2], [3]等等。我正在嘗試從主對象中獲取對象

//this works 
var collection = oData.events.event[0]; 
$("<li>description: " + collection.description + "</li>").appendTo("#shower"); 


//this does not work :(

var collection = oData.events.event[0]; 

var output = "<ul>"; 

for (var i = 0; i < collection.length; i++) 

{ 

    output += "<li>" + collection.description + "</li>"; 

    $(output).appendTo("#shower"); 

    collection = collection + 1 //shift to next array 

} 

output += "</ul>"; 

回答

0

也許使用foreach循環

oData.events.event.forEach(function(result) { 
    console.log(result); 
}); 

或者,嘗試jQuery的。每()函數:

$.each(oData.events.event, function(index, value) { 
    console.log(index + ": " + value); 
}); 

編輯:值得注意的是,這些調用的輸出將是一個對象 - 您仍然必須訪問您已經循環的對象下的數據!

0

Fiddle在這裏 - 不過,你可以做這樣的事情......

var oData = { 
    events: { 
     event: [{ description: '1' }, 
       { description: '2' }, 
       { description: '3' }] 
    } 
} 

var collection = oData.events.event; 
var output = "<ul>"; 

collection.forEach(function(item, i, arr) { 
    output += "<li>" + item.description + "</li>"; 
    if (i === arr.length-1) { 
     output += "</ul>"; 
     $("#shower").append(output); 
    } 
});