【问题标题】:Asynchronous looping through array with an object carrying another array异步循环遍历数组,对象携带另一个数组
【发布时间】:2014-07-12 16:43:54
【问题描述】:

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

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 控制要添加的行。

【问题讨论】:

  • ...那么什么不起作用,您尝试了什么?这个网站上有很多关于遍历数组和对象的答案。

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


【解决方案1】:

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

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, ...);

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

【讨论】:

  • 我认为这在 Windows Azure 移动服务 node.js api 中是不可能的。不过,谢谢你给我这个指针。在集合插入中找不到任何资源。
  • 如果没有任何集合插入,我猜你必须做嵌套的 async.each()。或者您仍然可以使用上面的方法将其展平,然后只在 async.each() 上执行(或 async.eachSeries() 如果您需要串行而不是并行执行)。
  • 对象何时被迭代并不重要,只要它为内部数组插入正确的顶级ID即可。我一定会采纳你的建议,非常感谢!
猜你喜欢
  • 2020-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-12
  • 1970-01-01
  • 2016-09-07
  • 1970-01-01
  • 2018-04-09
相关资源
最近更新 更多