Search code examples
javascriptlodash

How to get the difference between two objects?


If I have two objects:

const objA = { name: 'Tom', age: '20', location: 'London' };
const objB = { name: 'Jimmy', age: '35', occupation: 'Welder', hobbies: ['Football'] }

How can I get only the values that are only present in objA and not in objB, I want the result to be:

{
    location: 'London'
}

Is there a method in Lodash for that?


Solution

  • You can use _.pickBy() and _.has() to get the desired result using lodash.

    We'll use the predicate: (value, key) => !_.has(objB, key) to return entries only present in objA.

    const objA = { name: 'Tom', age: '20', location: 'London' };
    const objB = { name: 'Jimmy', age: '35', occupation: 'Welder', hobbies: ['Football'] }
    
    const difference = _.pickBy(objA, (value, key) => !_.has(objB, key));
    console.log('Difference:', difference)
       
    <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>

    You can also do this in vanilla JavaScript using Object.entries(), Object.fromEntries() and Array.filter():

    const objA = { name: 'Tom', age: '20', location: 'London' };
    const objB = { name: 'Jimmy', age: '35', occupation: 'Welder', hobbies: ['Football'] }
    
    const difference = Object.fromEntries(
        Object.entries(objA).filter(([key, value]) => {
            return !objB.hasOwnProperty(key);
        })
    );
    
    console.log('Difference:', difference)