我有一个带有这些值的数组,我需要在这些值上创建一个循环以在alasql中返回,如以下示例所示:
http://jsfiddle.net/agershun/11gd86nx/5/
var data = {
"business": [
{
"order_contents": [
{
"id": 83,
"name": "product 1",
"price": "1.99",
"quantity": 1,
"total": "1.99",
"ingredients": [],
"extras": []
},
{
"id": 83,
"name": "product 1",
"price": "1.99",
"quantity": 1,
"total": "1.99",
"ingredients": [],
"extras": []
},
{
"id": 83,
"name": "product 1",
"price": "1.99",
"quantity": 1,
"total": "1.99",
"ingredients": [],
"extras": []
},
{
"id": 85,
"name": "product 3",
"price": "1.99",
"quantity": 1,
"total": "1.99",
"ingredients": [],
"extras": []
},
{
"id": 83,
"name": "product 1",
"price": "1.99",
"quantity": 1,
"total": "1.99",
"ingredients": [],
"extras": []
},
{
"id": 84,
"name": "product 2",
"price": "1.99",
"quantity": 1,
"total": "1.99",
"ingredients": [],
"extras": []
},
{
"id": 83,
"name": "product 1",
"price": "1.99",
"quantity": 1,
"total": "1.99",
"ingredients": [],
"extras": []
},
{
"id": 83,
"name": "product 1",
"price": "1.99",
"quantity": 1,
"total": "1.99",
"ingredients": [],
"extras": []
},
{
"id": 83,
"name": "product 1",
"price": "1.99",
"quantity": 1,
"total": "1.99",
"ingredients": [],
"extras": []
},
{
"id": 83,
"name": "product 1",
"price": "1.99",
"quantity": 1,
"total": "1.99",
"ingredients": [],
"extras": []
},
{
"id": 83,
"name": "product 1",
"price": "1.99",
"quantity": 1,
"total": "1.99",
"ingredients": [],
"extras": []
},
{
"id": 83,
"name": "product 1",
"price": "1.99",
"quantity": 1,
"total": "1.99",
"ingredients": [],
"extras": []
},
{
"id": 84,
"name": "product 2",
"price": "1.99",
"quantity": 1,
"total": "1.99",
"ingredients": [],
"extras": []
}
]
}
]
};
这是我的代码..
info.orderByChild("data").startAt("08/04/2017").endAt("12/06/2017").on('value', function(snapshot){
snapshot.forEach(function(item) {
jsonObj = {
"business": [
{
"order_contents": [
{
"id": itemVal['id'],
"name": itemVal['name'],
"price": itemVal['price'],
"quantity": itemVal['quantity'],
"total": "itemVal['total']
}
]
}
]
}
它不创建数组,只创建最后一个值。
有人可以帮助我吗?
你必须在开始时定义你的数组,并在循环的后面添加每个对象:
var result = { business: [] }; // PLACEHOLDER
var jsonObj;
info.orderByChild("data").startAt("08/04/2017").endAt("12/06/2017").on('value', function(snapshot) {
snapshot.forEach(function(item) {
jsonObj = {
"order_contents": [
{
"id": itemVal['id'],
"name": itemVal['name'],
"price": itemVal['price'],
"quantity": itemVal['quantity'],
"total": "itemVal['total']
}
]
};
result.business.push(jsonObj); // ADDING EACH OBJECT TO YOUR ARRAY
});
});
您希望将
snapshot
中的项映射到新数组,因此不要使用 forEach
方法,而是使用 map
方法及其返回的结果数组:
jsonObj = snapshot.map(function(item) {
return {
"business": [
{
"order_contents": [
{
"id": item['id'],
"name": item['name'],
"price": item['price'],
"quantity": item['quantity'],
"total": item['total']
}
]
}
]
}
});