lodash 中是否有用于替换匹配项的函数

2022-08-30 02:05:46

我想知道在lodash中是否有更简单的方法来替换JavaScript集合中的项目?(可能重复,但我不明白那里的答案:)

我查看了他们的文档,但找不到任何内容

我的代码是:

var arr = [{id: 1, name: "Person 1"}, {id:2, name:"Person 2"}];
// Can following code be reduced to something like _.XX(arr, {id:1}, {id:1, name: "New Name"});
_.each(arr, function(a, idx){
  if(a.id === 1){
    arr[idx] = {id:1, name: "Person New Name"};
    return false;
  }
});

_.each(arr, function(a){
  document.write(a.name);
});

更新:我尝试替换的对象具有许多属性,例如

{id: 1, Prop1: ..., Prop2:..., 等等}

溶液:

感谢dfsq,但我在lodash中找到了一个适当的解决方案,它似乎工作正常并且非常整洁,我也把它放在mixin中,因为我在很多地方都有这个要求。金士斌

var update = function(arr, key, newval) {
  var match = _.find(arr, key);
  if(match)
    _.merge(match, newval);
  else
    arr.push(newval);    
};

_.mixin({ '$update': update });

var arr = [{id: 1, name: "Person 1"}, {id:2, name:"Person 2"}];

_.$update(arr, {id:1}, {id:1, name: "New Val"});


document.write(JSON.stringify(arr));

更快的解决方案正如@dfsq所指出的那样,遵循速度要快得多。

var upsert = function (arr, key, newval) {
    var match = _.find(arr, key);
    if(match){
        var index = _.indexOf(arr, _.find(arr, key));
        arr.splice(index, 1, newval);
    } else {
        arr.push(newval);
    }
};

答案 1

在你的情况下,你需要做的就是在数组中找到对象并使用方法,在这里阅读更多细节:Array.prototype.splice()

var arr = [{id: 1, name: "Person 1"}, {id:2, name:"Person 2"}];

// Find item index using _.findIndex (thanks @AJ Richardson for comment)
var index = _.findIndex(arr, {id: 1});

// Replace item at index using native splice
arr.splice(index, 1, {id: 100, name: 'New object.'});

// "console.log" result
document.write(JSON.stringify( arr ));
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js"></script>

答案 2

似乎最简单的解决方案是使用ES6或lodash的:.map_.map

var arr = [{id: 1, name: "Person 1"}, {id: 2, name: "Person 2"}];

// lodash
var newArr = _.map(arr, function(a) {
  return a.id === 1 ? {id: 1, name: "Person New Name"} : a;
});

// ES6
var newArr = arr.map(function(a) {
  return a.id === 1 ? {id: 1, name: "Person New Name"} : a;
});

这具有避免改变原始数组的良好效果。