So I have an array of objects like that:
var arr = [
{uid: 1, name: bla, description: cucu},
{uid: 2, name: smth else, description: cucarecu},
]
uid
is unique id of the object in this array. I'm searching for the elegant way to modify the object if we have the object with the given uid,
or add a new element, if the presented uid
doesn't exist in the array. I imagine the function to be behave like that in js console:
> addOrReplace(arr, {uid: 1, name: 'changed name', description: changed description})
> arr
[
{uid: 1, name: bla, description: cucu},
{uid: 2, name: smth else, description: cucarecu},
]
> addOrReplace(arr, {uid: 3, name: 'new element name name', description: cocoroco})
> arr
[
{uid: 1, name: bla, description: cucu},
{uid: 2, name: smth else, description: cucarecu},
{uid: 3, name: 'new element name name', description: cocoroco}
]
My current way doesn't seem to be very elegant and functional:
function addOrReplace (arr, object) {
var index = _.findIndex(arr, {'uid' : object.uid});
if (-1 === index) {
arr.push(object);
} else {
arr[index] = object;
}
}
I'm using lodash, so I was thinking of something like modified _.union
with custom equality check.