我正在尝试从主对象中获取对象
I am trying to fetch objects from a main object
我正在尝试从主对象中获取对象。主对象中的数组包含
这些其他对象,我可以通过调用 '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>";
也许使用 foreach 循环
oData.events.event.forEach(function(result) {
console.log(result);
});
或者,尝试 jQuery 的 .each() 函数:
$.each(oData.events.event, function(index, value) {
console.log( index + ": " + value );
});
编辑:值得注意的是,这些调用的输出将是一个对象——您仍然必须访问循环到的对象下的数据!
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);
}
});
我正在尝试从主对象中获取对象。主对象中的数组包含
这些其他对象,我可以通过调用 '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>";
也许使用 foreach 循环
oData.events.event.forEach(function(result) {
console.log(result);
});
或者,尝试 jQuery 的 .each() 函数:
$.each(oData.events.event, function(index, value) {
console.log( index + ": " + value );
});
编辑:值得注意的是,这些调用的输出将是一个对象——您仍然必须访问循环到的对象下的数据!
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);
}
});