ganqqwerty
ganqqwerty

Reputation: 1994

Update if exists or add new element to array of objects - elegant way in javascript + lodash

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.

Upvotes: 47

Views: 91120

Answers (9)

tanguy_k
tanguy_k

Reputation: 12303

In your first approach, no need for Lodash thanks to findIndex():

function upsert(array, element) { // (1)
  const i = array.findIndex(e => e.id === element.id);
  if (i > -1) array[i] = element; // (2)
  else array.push(element);
}

Example:

const array = [
  {id: 0, name: 'Apple', description: 'fruit'},
  {id: 1, name: 'Banana', description: 'fruit'},
  {id: 2, name: 'Tomato', description: 'vegetable'}
];

upsert(array, {id: 2, name: 'Tomato', description: 'fruit'})
console.log(array);
/* =>
[
  {id: 0, name: 'Apple', description: 'fruit'},
  {id: 1, name: 'Banana', description: 'fruit'},
  {id: 2, name: 'Tomato', description: 'fruit'}
]
*/

upsert(array, {id: 3, name: 'Cucumber', description: 'vegetable'})
console.log(array);
/* =>
[
  {id: 0, name: 'Apple', description: 'fruit'},
  {id: 1, name: 'Banana', description: 'fruit'},
  {id: 2, name: 'Tomato', description: 'fruit'},
  {id: 3, name: 'Cucumber', description: 'vegetable'}
]
*/

(1) other possible names: addOrReplace(), addOrUpdate(), appendOrUpdate(), insertOrUpdate()...

(2) can also be done with array.splice(i, 1, element)

Note that this approach is "mutable" (vs "immutable"): it means instead of returning a new array (without touching the original array), it modifies directly the original array.

Upvotes: 69

pgarciacamou
pgarciacamou

Reputation: 1732

I personally do not like solutions that modify the original array/object, so this is what I did:

function addOrReplaceBy(arr = [], predicate, getItem) {
  const index = _.findIndex(arr, predicate);
  return index === -1
    ? [...arr, getItem()]
    : [
      ...arr.slice(0, index),
      getItem(arr[index]),
      ...arr.slice(index + 1)
    ];
}

And you would use it like:

var stuff = [
  { id: 1 },
  { id: 2 },
  { id: 3 },
  { id: 4 },
];

var foo = { id: 2, foo: "bar" };
stuff = addOrReplaceBy(
  stuff,
  { id: foo.id },
  (elem) => ({
    ...elem,
    ...foo
  })
);

What I decided to do was to make it more flexible:

  1. By using lodash -> _.findIndex(), the predicate can be multiple things
  2. By passing a callback getItem(), you can decide whether to fully replace the item or do some modifications, as I did in my example.

Note: this solution contains some ES6 features such as destructuring, arrow functions, among others.


There is a second approach to this. We can use JavaScript Map object which "holds key-value pairs and remembers the original insertion order of the keys" plus "any value (both objects and primitive values) may be used as either a key or a value."

let myMap = new Map(
  ['1', { id: '1', first: true }] // key-value entry
  ['2', { id: '2', second: true }]
)

myMap = new Map([
  ...myMap, 
  ['1', { id: '1', first: true, other: '...' }]
  ['3', { id: '3', third: true }]
])

myMap will have the following entries in order:

['1', { id: '1', first: true, other: '...' }]
['2', { id: '2', second: true }]
['3', { id: '3', third: true }]

We can use this characteristic of Maps to add or replace other elements:

function addOrReplaceBy(array, value, key = "id") {
  return Array.from(
    new Map([
      ...array.map(item => [ item[key], item ]),
      [value[key], value]
    ]).values()
  )
}

Upvotes: 9

Julian
Julian

Reputation: 4366

Backbone.Collection provides exactly this functionality. Save yourself the effort when you can!

var UidModel = Backbone.Model.extend({
    idAttribute: 'uid'
});

var data = new Backbone.Collection([
    {uid: 1, name: "bla", description: "cucu"},
    {uid: 2, name: "smth else", description: "cucarecu"}
], {
    model: UidModel
});

data.add({uid: 1, name: 'changed name', description: "changed description"}, {merge: true});

data.add({uid: 3, name: 'new element name name', description: "cocoroco"});

console.log(data.toJSON());

Upvotes: 0

MrP
MrP

Reputation: 94

really complicated solutions :D Here is a one liner:

const newArray = array.filter(obj => obj.id !== newObj.id).concat(newObj)

Upvotes: 5

IngoP
IngoP

Reputation: 515

If you do not mind about the order of the items in the end then more neat functional es6 approach would be as following:

function addOrReplace(arr, newObj){ 
 return [...arr.filter((obj) => obj.uid !== newObj.uid), {...newObj}];
}

// or shorter one line version 

const addOrReplace = (arr, newObj) => [...arr.filter((o) => o.uid !== newObj.uid), {...newObj}];

If item exist it will be excluded and then new item will be added at the end, basically it is replace, and if item is not found new object will be added at the end.

In this way you would have immutable list. Only thing to know is that you would need to do some kind of sort in order to keep list order if you are for instance rendering list on the screen.

Hopefully, this will be handy to someone.

Upvotes: 21

Chris Sullivan
Chris Sullivan

Reputation: 1041

Old post, but why not use the filter function?

// If you find the index of an existing uid, save its index then delete it
//      --- after the filter add the new object.
function addOrReplace( argh, obj ) {
  var index = -1;
  argh.filter((el, pos) => {
    if( el.uid == obj.uid )
      delete argh[index = pos];
    return true;
  });

  // put in place, or append to list
  if( index == -1 ) 
    argh.push(obj);
  else 
    argh[index] = obj;
}

Here is a jsfiddle showing how it works.

Upvotes: 3

friedi
friedi

Reputation: 4360

You can use an object instead of an array:

var hash = {
  '1': {uid: 1, name: "bla", description: "cucu"},
  '2': {uid: 2, name: "smth else", description: "cucarecu"}
};

The keys are the uids. Now your function addOrReplace is simple like this:

function addOrReplace(hash, object) {
    hash[object.uid] = object;
}

UPDATE

It's also possible to use an object as an index in addition to the array.
This way you've got fast lookups and also a working array:

var arr = [],
    arrIndex = {};

addOrReplace({uid: 1, name: "bla", description: "cucu"});
addOrReplace({uid: 2, name: "smth else", description: "cucarecu"});
addOrReplace({uid: 1, name: "bli", description: "cici"});

function addOrReplace(object) {
    var index = arrIndex[object.uid];
    if(index === undefined) {
        index = arr.length;
        arrIndex[object.uid] = index;
    }
    arr[index] = object;
}

Take a look at the jsfiddle-demo (an object-oriented solution you'll find here)

Upvotes: 24

Tomalak
Tomalak

Reputation: 338316

Maybe

_.mixin({
    mergeById: function mergeById(arr, obj, idProp) {
        var index = _.findIndex(arr, function (elem) {
            // double check, since undefined === undefined
            return typeof elem[idProp] !== "undefined" && elem[idProp] === obj[idProp];
        });

        if (index > -1) {
            arr[index] = obj; 
        } else {
            arr.push(obj);
        }

        return arr;
    }
});

and

var elem = {uid: 3, name: 'new element name name', description: "cocoroco"};

_.mergeById(arr, elem, "uid");

Upvotes: 4

Drecker
Drecker

Reputation: 1265

What about having the indexes of the array same as the uid?, like:

arr = [];
arr[1] = {uid: 1, name: "bla", description: "cucu"};
arr[2] = {uid: 2, name: "smth else", description: "cucarecu"};

that way you could just simply use

arr[affectedId] = changedObject;

Upvotes: 1

Related Questions