简体   繁体   English

lodash:对象数组

[英]lodash: Array of Objects

I have an node.js array of objects like so - 我有一个像这样的对象的node.js数组-

[
    { sid: 1095, a: 484, b: 'someval1' },
    { sid: 1096, a: 746, b: 'someval5' },
    { sid: 1097, a: 658, b: 'someval7' },
    { sid: 1098, a: 194, b: 'someval3' }
]

a) Is it possible to update and delete members of the array in-place based on sid and wouldn't slow things down performance-wise? a)是否可以基于sid 在原位更新和删除数组成员,并且不会降低性能?

b) If I needed to chunk the array and fire off async code against the chunks ( say insert into a DB, 100 records at a time ) how would async blend with lodash's synchronous code? b)如果我需要对数组进行分块并针对该分块触发异步代码(例如,一次插入100个记录到一个DB中),异步将如何与lodash的同步代码融合?

Pointers are appreciated. 指针表示赞赏。

a) There are two ways to accomplish this. a)有两种方法可以做到这一点。 First, you could instantiate an object using var newArr = _.keyBy(arr, 'sid'); 首先,您可以使用var newArr = _.keyBy(arr, 'sid');实例化对象var newArr = _.keyBy(arr, 'sid'); . Then you could reference the item you want to edit directly newArr[sid].a = 494 . 然后,您可以引用要直接编辑的项目newArr[sid].a = 494 Another option would be to use a combination of _.indexOf and _.find , so var index = _.indexOf(arr, _.find(arr, { sid: sid })); 另一种选择是使用_.indexOf_.find的组合,因此var index = _.indexOf(arr, _.find(arr, { sid: sid })); and then edit it using the index arr[index].a = 494 然后使用index arr[index].a = 494对其进行编辑

b) lodash has a method _.chunk . b)lodash有一个方法_.chunk So 所以

var chunked = _.chunk(arr, 100);
var promises = chunked.map(item => db.bulkInsert(item));

Promise.all(promises)
  .then(result => {
    // Do whatever else you want
  });

I hope this is helpful. 我希望这是有帮助的。 On b) it is a little hard to give specific advise without knowing how you are handling DB operations (using an ORM, building queries by hand, etc). 在b)上,在不知道您如何处理数据库操作(使用ORM,手动构建查询等)的情况下,给出具体建议有些困难。 But the basic idea (assuming you are using promises, which you should be) is that you want generate an array of promises representing each bulk insert. 但是,基本思想(假设您正在使用的是Promise)应该是要生成一个表示每个批量插入内容的Promise数组。 And then do something once they are all resolved. 解决所有问题后,再执行一些操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM