【问题标题】:Lodash collection bulk updateLodash 集合批量更新
【发布时间】:2016-12-27 07:42:41
【问题描述】:

我想要一些这样的代码:

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

换句话说,我想通过字符串或函数来更新我的集合中的一个字段,我知道这个函数存在,但不知道它的名字

【问题讨论】:

    标签: javascript collections lodash


    【解决方案1】:

    您可以使用_.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>

    【讨论】:

      【解决方案2】:

      尝试使用_.update_.updateWith

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-11-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-15
        • 1970-01-01
        • 2014-12-19
        相关资源
        最近更新 更多