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}
答案 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;