gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 12:33:36 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com