Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How delete properties of one object that are not in another object

Say I have two objects like the ones below.

let a = {Friday: [1, 2 3], Saturday: [2,4,2], Sunday: [1,4]}
let b = {Friday: [], Saturday: []}

I need some sort of way to delete all the key value pairs from a that are not in b, so the result would be:

{Friday: [1, 2 3], Saturday: [2,4,2]}
like image 840
Oamar Kanji Avatar asked Oct 28 '25 01:10

Oamar Kanji


1 Answers

simply use a for loop and delete:

  • Iterate over all the properties in a
  • check if the property exist in b, if it is not present simply delete the property from a.

let a = {Friday: [1, 2, 3], Saturday: [2,4,2], Sunday: [1,4]};
let b = {Friday: [], Saturday: []};

for(let key in a){
  if(!(key in b))
    delete a[key];
}
console.log(a);
like image 146
amrender singh Avatar answered Oct 31 '25 09:10

amrender singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!