Reputation: 1317
I'm using lodash to compare two arrays of objets with differentWith (isEqual) function.
Here my two arrays:
array1
[
{
"id":"28884",
"designation":"French fries",
"description":"French fries",
"prices":[
{
"price":0,
"vat":2821
}
]
},
{
"id":"28885",
"designation":"Potatoes",
"description":"Potatoes",
"prices":[
{
"price":0,
"vat":2821
}
]
}
]
array2
[
{
"id":"28884",
"designation":"French fries",
"description":"French fries",
"prices":[
{
"price":0,
"vat":2821
}
]
},
{
"id":"28885",
"designation":"Potatoes",
"description":"Potatoes",
"prices":[
{
"price":0,
"vat":2821
}
]
},
{
"id":"30157",
"designation":"new item",
"description":null,
"prices":[
{
"price":500,
"vat":2821
}
]
}
]
Here what I did but it doesn't work :
const toAdd = _.differenceWith(array1, array2, _.isEqual);
const toRemove = _.differenceWith(array2, array1, _.isEqual);
How can I get removed element(s) ? Moreover, How can I get the new elements, removed elements using lodash ? Thank you !
Upvotes: 0
Views: 673
Reputation: 106
You can use _.differenceBy . _.intersectionBy for comparision with key in case of array of objects.
let toRemove = _.differenceBy(array2, array1, 'id');
let toAdd = _.intersectionBy(array1, array2, 'id');
Upvotes: 0
Reputation: 6015
The problem is the comparator in the code _.isEqual
cannot compare two objects
in the array. You could write a custom comparator.
A simpler vanilla js option may be
removedObjectsArray = array2.filter(item => !array1.map(obj => obj.id).includes(item.id));
Here the larger array is filtered to find items which have an id that is not in the smaller array.
Upvotes: 1