Reputation: 65
I know how to delete a JSON element using delete option. But I have a situation
I have two JSON objects like
var a = {
key1 : 'v1',
key2 : 'v2',
key3 : 'v3',
key4 : 'v4'
}
var b = {
key1 : 'v1',
key3 : 'v3',
key5 : 'v5'
}
now I want a minus b (i.e) delete elements in "var a" that present in "var b". I need my result as
{
key2 : 'v2',
key4 : 'v4'
};
Is there any method available for this? Thanks in advance...
Upvotes: 0
Views: 41
Reputation: 33736
If you don't want to mutate the source object, you can use the function Array.prototype.reduce
as follow:
This approach compares both the key and value, however, if this is not the desired behavior, you can remove the value comparison
let a = { key1 : 'v1', key2 : 'v2', key3 : 'v3', key4 : 'v4' },
b = { key1 : 'v1', key3 : 'v3', key5 : 'v5'},
bEntries = Object.entries(b);
let result = Object.entries(a).reduce((a, [k, v]) => {
if (!bEntries.some(([bk, bv]) => k === bk && v === bv)) {
return Object.assign(a, {[k]: v});
}
return a;
}, Object.create(null));
console.log(result);
Upvotes: 0
Reputation: 74
Going for an immutable approach (i.e. you don't modify neither a
or b
), all you need to check is if key k
in a
(as in a[k]
) is not present in b
(as in b[k]
doesn't exist).
function objDifference(a, b) {
let output = {}
Object.keys(a).forEach((k) => {
if (!(k in b)) { // If object b doesn't have the k key
output[k] = a[k]
}
})
return output;
}
function objDifference(a, b) {
let output = {}
Object.keys(a).forEach((k) => {
if (!(k in b)) {
output[k] = a[k]
}
})
return output;
}
var a = {
key1 : 'v1',
key2 : 'v2',
key3 : 'v3',
key4 : 'v4'
}
var b = {
key1 : 'v1',
key3 : 'v3',
key5 : 'v5'
}
console.log(objDifference(a, b))
Upvotes: 0
Reputation: 8515
The simplest approach is to simply iterate over b
keys and delete all of the keys in a
that are present there:
var a = {
key1 : 'v1',
key2 : 'v2',
key3 : 'v3',
key4 : 'v4'
}
var b = {
key1 : 'v1',
key3 : 'v3',
key5 : 'v5'
}
for (let key in b) {
if (a.hasOwnProperty(key)) {
delete a[key];
}
}
console.log(a);
Upvotes: 1
Reputation: 1040
for(let key of Object.keys(a)) {
if(b.hasOwnProperty(key)) {
delete a[key]
}
}
Upvotes: 2