Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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");
like image 959
sith Avatar asked Feb 16 '17 05:02

sith


People also ask

How do you update an item in an array?

To update an object in a JavaScript array, you can use “findIndex()” method for executing each array element and updating the object values accordingly, the “for” loop method for iterating through an array and updating the specified value, and “map()” method for mapping the updated value to an object.

What does .value do in Lodash?

values() Method. The _. values() method is used to return the array of the own enumerable string keyed property values of the object.

Is Lodash still needed 2022?

But Sometimes You Do Need Lodash Not every Lodash utility is available in Vanilla JavaScript. You can't deep clone an object, for example. That's why these libraries are far from obsolete. But if you're loading the entire library just to use a couple of methods, that's not the best way to use the library.


2 Answers

you can do it with _.unionBy

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

but check a note at this comment

like image 54
stasovlas Avatar answered Sep 29 '22 23:09

stasovlas


You can use .findIndex()

var i = arr.findIndex(o => o.id === obj.id);
if (arr[i]) { arr[i] = obj } else { arr.push(obj) };
like image 42
guest271314 Avatar answered Sep 30 '22 00:09

guest271314