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");
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.
values() Method. The _. values() method is used to return the array of the own enumerable string keyed property values of the object.
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.
you can do it with _.unionBy
var res = _.unionBy([obj], arr, 'id');
but check a note at this comment
You can use .findIndex()
var i = arr.findIndex(o => o.id === obj.id);
if (arr[i]) { arr[i] = obj } else { arr.push(obj) };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With