The following is working code. The question is specifically about refactoring to provide the string for property name used to compare by isSame
. Perhaps better renamed to isPropValueSame
.
import * as _ from 'lodash';
const diff = _.differenceWith(sourceList, comparatorList, this.isSame);
isSame = (objA: any, objB: any) => (_.has(objA, 'id') && _.has(objB, 'id') ? objA['id'] === objB['id'] : false);
Looking to pass field/prop name string like this.isSame('id'))
;
objA
and objB
would be the items from lists: sourceList
and comparatorList
and lists might look like:
const sourceList = [
{ id: 1, prop2: { prop21: someValue }, prop3: prop3Value },
{ id: 2, prop2: { prop21: someValue }, prop3: prop3Value },
{ id: 3, prop2: { prop21: someValue }, prop3: prop3Value },
];
const comparatorList = [
{ id: 1, prop2: { prop21: someValue }, prop3: prop3Value },
//{ id: 2, prop2: { prop21: someValue }, prop3: prop3Value },
{ id: 3, prop2: { prop21: someValue }, prop3: prop3Value },
];
With above test case data (note comparatorList
has second item commented out), then the output of comparator would return the item where id
equals 2
because it does not find it during comparison by delegate function isSame
.