skip to Main Content

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


  1. 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:

    const isSame = (key: string) => (objA: unknown, objB: unknown) =>
      _.has(objA, key) && _.has(objB, key) && _.get(objA, key) === _.get(objB, key);
    

    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.

    Login or Signup to reply.
  2. One option is to use a closure to which you pass the prop/attribute of interest:

    const isSame = (prop) => {
      const issame = (a, b) => (_.has(a, prop) && _.has(b, prop) ? a[prop] === b[prop] : false);
      return issame;
    };
    
    const someValue = 42;
    const prop3Value = 3;
    
    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 },
    ];
    
    console.log(_.differenceWith(sourceList, comparatorList, isSame("id")));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search