Reputation: 4249
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?
Upvotes: 0
Views: 2602
Reputation: 56754
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:
Object.entries()
(ES 2017)Object.fromEntries()
(ES 2019)Object.hasOwn()
(ES 2022)Upvotes: 4
Reputation: 30685
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)
Upvotes: 2
Reputation: 141
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);
Upvotes: 0