[Solved] How to replace an object in object array in javascript (lodash)

I have following object array:

var arr = [
  {
    id    : "a1",
    guid  : "sdfsfd",
    ...
    value : "abc",
    status: false
  },
  {
    id    : "a2",
    guid  : "sdfsfd",
    ...
    value : "def",
    status: true
  },
  ...
]

I have this object:

var obj = {
  id      : "a1",
  guid    : "sdfsfd",
  ...
  value   : "xyz",
  status  :  true
}

I need to replace the object in the array with this object where the “id” is same. So the resulting array will be:

var arr = [
  {
    id    : "a1",
    guid  : "sdfsfd",
    ...
    value : "xyz",
    status: true
  },
  {
    id    : "a2",
    guid  : "sdfsfd",
    ...
    value : "def",
    status: true
  },
  ...
]

Additionally I need to add this object to the array if an object with that id doesn’t exists.

How to achieve this using minimal lodash code?
Looking for something like

arr = _.merge_by_key(arr,obj,"id");
Enquirer: sith

||

Solution #1:

you can do it with _.unionBy

var res = _.unionBy([obj], arr, 'id');

but check a note at this comment

Respondent: stasovlas

Solution #2:

You can use .findIndex()

var i = arr.findIndex(o => o.id === obj.id);
if (arr[i]) { arr[i] = obj } else { arr.push(obj) };
Respondent: guest271314

Solution #3:

You can use _.findIndex with the _.matchesProperty shorthand:

var index = _.findIndex(arr, ['id', obj.id]);
arr[index >= 0 ? index : arr.length] = obj;

Respondent: 4castle

Solution #4:

Here’s a lodash solution that uses keyBy to create an object wherein each item in the collection is represented by their id, set to override the new object or possibly add the new object and lastly values to get the array representation of the object.

var result = _(arr).keyBy('id').set(obj.id, obj).values().value();

Respondent: ryeballar

Solution #5:

you can loop and use ‘splice’ function:

var added = false;
for(var i=0;i<arr.length; i++){
   if(arr[i].id === obj.id){
        arr.splice(i,1,obj);
        added = true;
        break;
   }
}

if(!added) arr.push(obj);

EDIT: missed added condition

Respondent: Asad Sarwar

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.