Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
-6
rated 0 times [  0] [ 6]  / answers: 1 / hits: 17185  / 7 Years ago, thu, february 16, 2017, 12:00:00

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);

More From » lodash

 Answers
1

you can do it with _.unionBy



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


but check a note at this comment


[#58918] Tuesday, February 14, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaycoborionc

Total Points: 220
Total Questions: 106
Total Answers: 120

Location: Kenya
Member since Mon, Jun 14, 2021
3 Years ago
;