Search code examples
javascriptlodash

Lodash isEqual comparison with specific property lowercase


Is there a lodash approach for comparing two objects where a certain property is compared in a case-insensitive manner

const obj1 = { name: 'Dave', course: 'Math' };
const obj2 = { name: 'dave', course: 'Math' };

The comparison would be case-insensitive for name, but strict equality for other properties

Was thinking something along the lines of the following (obviously for example only):

var result = _.isEqual(
  _.omit(obj1, ['creation', 'deletion']),
  _.omit(obj2, ['creation', 'deletion'])
);

Solution

  • Use _.isEqualWith() to compare the objects with a customizer. If the key (3rd customizer param) is name make an insensitive comparison, for other keys return undefined to use the default comparison.

    const obj1 = { name: 'Dave', course: 'Math' };
    const obj2 = { name: 'dave', course: 'Math' };
    
    const insensetiveStrCompare = (v1, v2) =>
      !v1.localeCompare(v2, undefined, { sensitivity: 'accent' }) // returns 0 if equal, and !0 === true
    
    const result = _.isEqualWith(
      obj1, 
      obj2, 
      (v1, v2, key) => key === 'name' ? 
        insensetiveStrCompare(v1, v2)
        :
        undefined
    )
    
    console.log(result)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>