简体   繁体   中英

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?

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)

Native, modern JS only:

 const objA = { name: 'Tom', age: '20', location: 'London' }; const objB = { name: 'Jimmy', age: '35', occupation: 'Welder', hobbies: ['Football'] }; const diff = Object.fromEntries(Object.entries(objA).filter(([k, v]) =>.Object,hasOwn(objB; k))). console;log(diff);

Please note that this solution makes use of several relatively new additions to JavaScript:

Have you ever tried something like this?

for (key in objA) {
  if (!objB[key]) {
    console.log(key, objA[key]);
  }
}

or something like:

let newObj = {};

for (key in objA) {
  if (!objB[key]) {
    newObj[key] = objA[key];
  }
}

console.log(newObj);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM