Skip to content

Instantly share code, notes, and snippets.

@uhtred
Created November 27, 2015 15:03
Show Gist options
  • Save uhtred/0042befce7059d9b492e to your computer and use it in GitHub Desktop.
Save uhtred/0042befce7059d9b492e to your computer and use it in GitHub Desktop.
Lodash Mixin to update a collection
/*
var list = [
{id: 1, name:"A"}
]
var oldItem = {id: 1, name:"AAA"}
_.update(list, oldItem);
// → [
{id: 1, name:"AAA"}
]
var newItem = {id: 2, name:"B"}
_.update(list, newItem);
// → [
{id: 1, name:"A"},
{id: 2, name:"B"}
]
*/
(function() {
'use strict';
function update(list, item, key) {
key = key || 'id';
var listItem = _.find(list, key, item[key]);
listItem ? _.assign(listItem, item) : list.push(item);
return list;
}
_.mixin({
'update': update
});
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment