javascript - 使用携带另一个数组的对象异步循环数组

标签 javascript arrays node.js asynchronous azure-sql-database

我有以下数组,其中包含一些属性和一个包含更多对象的数组。

var array = [
    {
        prop1Name: 'Thing',
        prop2ID: 1
        propArray: [
            {
                innerProp1Name: 'Name 1',
                innerProp2ID: 1
            },
            {
                innerProp1Name: 'Name 2',
                innerProp2ID: 2
            },
        ]
    },
    {
        prop1Name: 'Thing 2',
        prop2ID: 2
        propArray: [
            {
                innerProp1Name: 'Name 1',
                innerProp2ID: 1
            },
            {
                innerProp1Name: 'Name 2',
                innerProp2ID: 2
            },
        ]
    }
]

现在,我的目标是通过 Node.JS API 将其插入数据库。我已经涉足 async.js,但我想知道 async.each() 内部的 async.each() 是否是这里的方法。也许我可以在第一个 async.each() 的迭代器函数内部定义它。

该表需要 propArray 中每个条目的外部属性的 ID。 PropArray 控制要添加的行。

最佳答案

当数组和嵌套数组很大时,循环嵌套数组并为每个条目执行数据库插入非常昂贵。如果 db 驱动程序允许您执行数组插入(大多数情况下都这样做),则使用常规 for 循环将其展平并执行 1 db 插入会更便宜。像这样的东西:

var array = [ ... ];  // your array
var i, j, outLen, inLen, item, innerItem;
var result = [];

for (i = 0, outLen = array.length; i < outLen; i++) {
  item  = array[i];
  for (j = 0, inLen = item.propArray.length; j < inLen; j++) {
    innerItem = item.propArray[j];
    result.push({
      prop1Name: item.prop1Name,
      prop2ID: item.prop2ID,
      innerProp1Name: innerItem.innerProp1Name,
      innerProp2ID: innerItem.innerProp2ID
    });
  }
}

db.collection.insert(result, ...);

这没有任何错误检查和内部数组的存在。您可能想这样做。

关于javascript - 使用携带另一个数组的对象异步循环数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23827260/

相关文章:

javascript - 当登陆已经有一个 init 的路线/模板时,meteor-bootstrap-datetimepicker 会出现错误

Node.js 安装 - CentOS 6.9

javascript - 在 chrome 下弹出一个窗口

javascript - 在 Javascript/jQuery 中读取和显示 XML 内容

javascript - 在对象数组中,返回任何值与特定字符串匹配的对象

c - 如何打印出存储在二维数组中的字符串记录?

javascript - 获取稀疏 JavaScript 数组的第一个元素

javascript - 如何从 contenteditable div 中提取文本(但不是 html 标签)

javascript - Kendo Grid MVVM 与 rowtemplate 绑定(bind)到事件错误

node.js - 如何测试sequelize查询(where)逻辑?