2015-07-10 76 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); 
    } 
});