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
.
2
Answers
Not sure if you’re looking for more than just a closure around the key – doesn’t seem like type-safety is a concern for you so could be as simple as:
Sandbox
If you can live without having type checking on the key then that would suffice, but if you need it then I’d refer you to this previous answer on recursive access paths.
One option is to use a closure to which you pass the prop/attribute of interest: