简体   繁体   中英

lodash: Array of Objects

I have an node.js array of objects like so -

[
    { 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?

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?

Pointers are appreciated.

a) There are two ways to accomplish this. First, you could instantiate an object using var newArr = _.keyBy(arr, 'sid'); . Then you could reference the item you want to edit directly 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 })); and then edit it using the index arr[index].a = 494

b) lodash has a method _.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). 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. And then do something once they are all resolved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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