简体   繁体   English

Lodash集合批量更新

[英]Lodash collection bulk update

I want some code like this: 我想要这样的代码:

_.bulkUpdate(myCollection,'meta.type','new');

In other words, I want to update a field in my collection by a string or function, I know that this function is exist, but dont know its name 换句话说,我想通过字符串或函数更新集合中的字段,我知道此函数存在,但不知道其名称

You can bulk update in place by using _.forEach() to iterate the array, and then _.set() values, or _.update() using a function: 您可以使用_.forEach()迭代数组,然后使用_.set()值或_.update()进行批量更新,使用以下函数:

 var arr = [{ id: 1 }, { id: 2 }, { id: 3 }]; _.forEach(arr, function(item, index) { _.set(item, 'meta.type', 'new'); // to set a value _.update(item, 'meta.value', function() { return index; }); // to set with a function }); console.log(arr); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.3/lodash.min.js"></script> 

尝试使用_.update_.updateWith

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

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