Search code examples
javascriptobject

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]}

Solution

  • 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);