【发布时间】:2014-03-17 00:39:48
【问题描述】:
我正在尝试从数据库对象创建数组:
我有实体“组”,其中有许多“设备”,我想创建所有组的数组,并为每个组创建他的设备列表:
[
{
"group_id": “1”,
"name": “My_group”,
"devices_list": [1, 2, 18]
},
{
"group_id": “2”,
"name": “My_second_group”,
"devices_list": [3, 24]
}
]
我尝试了几种这样的方法:
Group.all(function (err, groups) {
var resJson = {};
groups.forEach(function(group, index){
group.devices(function(err, devices){
resJson[index] = group;
console.log(devices);
resJson[index].devices_list = devices;
//End of the loop
if (index == groups.length -1){
send({code: 200, data: resJson});
}
});
});
});
编辑 1:
我也试过这种方法:
var resJson = {};
groups.forEach(function(group, index){
group.devices(function(err, devices){
resJson[index] = group;
resJson[index].devices_list = [];
devices.forEach(function(device,index2){
resJson[index].devices_list.push(device);
});
//End of the loop
if (index == groups.length -1){
send({code: 200, data: resJson});
}
});
});
但最后,我的 resJson 只包含空组(没有关联设备的组),其他组不可见。因此,我的 devices_list 都是空的,而 console.log(devices) 显示设备。
看来“发送”指令是在处理非空组之前处理的。
这样做的正确方法是什么?
感谢您的宝贵时间
【问题讨论】:
-
这不应该是怎么回事,但我很好奇它是否是
resJson[index].devices_list = devices;行 - 您是否尝试过循环设备并将它们添加到设备列出来看看这是否会改变你的回报?此外,您的resJson是一个对象,而不是像您的目标 JSON 那样的数组。 -
感谢您的关注,我试过了,我编辑了我的帖子。
标签: arrays database json node.js control-flow