I am looking for a more concise way to add or replace an object within an array.
var arr = [
{uid: 1, name: "bla", description: "cucu"},
{uid: 2, name: "smth else", description: "cucarecu"},
]
Here is a new object:
var mynewObject = {uid: 1, name: "newBlabla", description: "newDesc"};
Currently, I am using the following function to achieve this:
function addOrReplace (arr, object) {
var index = arr.findIndex(x => object.uid === x.uid);
if (-1 === index) {
arr.push(object);
} else {
arr[index] = object;
}
return arr;
}
However, I find this method somewhat cumbersome. Is there a more elegant way to accomplish this in just one or two lines?
The original array must remain intact and the new object should only be checked by its uid
property.