替换阵列中的mached元素,Lodash

时间:2017-01-06 12:38:34

标签: javascript lodash

function replaceById(requests, request) {
    requests.splice(_.indexOf(requests, _.find(requests, {id: request.id})), 1, request);
}

Lodash(或其他实用程序库)是否提供了任何方法来简化数组request中的特定元素requests的替换,例如

function(r) { return _.eq(r.id, request.id); }

或像

这样的身份对象
{id: request.id}

1 个答案:

答案 0 :(得分:1)

您可以使用findIndex

function replaceById(requests, request) {
  var index = _.findIndex(requests, function(r) { 
    return r.id === request.id 
  });
  requests.splice(index, 1, request);
}



function replaceById(requests, request) {
  var index = _.findIndex(requests, function(r) { 
    return r.id === request.id 
  });
  requests.splice(index, 1, request);
}

var requests = [{id: 1, msg: 'cool'}, {id: 2, msg: 'wow'}];
replaceById(requests, {id: 2, msg: 'stuff'});
console.log(requests);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
&#13;
&#13;
&#13;