Created
November 27, 2015 15:03
-
-
Save uhtred/0042befce7059d9b492e to your computer and use it in GitHub Desktop.
Lodash Mixin to update a collection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| 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