Search code examples
javascriptarraysobjectintersection

Intersection of an array with a deeply nested object in javascript


I want to include all the keys of an object present in an array and discard the rest, For e.g., if I have an array,

const arr = ['apple', 'milk', 'bread', 'coke'];

and an object,

const dummy = {
    apple: {
        category: 'fruit'
    },
    banana: {
        category: 'fruit'
    },
    potato: {
        category: 'vegetable'
    },
    dairy: {
        milk: {
          type: 'A2'
        }
    },
    bakery: {
        bread: {
            type: 'brown'
        }
    },
    beverage: {
      cold_drink: {
        coke: {
          type: 'diet'
        },
        beer: {
        }
      }
    }
}

I want my resultant object to contain the keys from arr only, be it direct keys or deeply nested. So for above case, my resultant object will look like,

{
    apple: {
        category: 'fruit'
    },
    dairy: {
        milk: {
          type: 'A2'
        }
    },
    bakery: {
        bread: {
            type: 'brown'
        }
    },
    beverage: {
      cold_drink: {
        coke: {
          type: 'diet'
        },
        beer: {}
      }
    }
}

I am trying to solve this via recursion, but not able to get the output correctly. Below is my code, could you please help me with where I am going wrong?

function fetchResultantObject(object, key, result) {
  if(typeof object !== 'object')
    return null;
  for(let objKey in object) {
    if(key.indexOf(objKey) > -1) {
      result[objKey] = object[objKey];
    } else {
      result[objKey] = fetchValueByKey(object[objKey], key, result);
    }
  }
  return result;
}

console.log(fetchResultantObject(dummy, arr, {}));

Solution

  • You could filter the entries and check if the (nested) objects contains a wanted key.

    const
        hasKey = object => object
            && typeof object === 'object'
            && (keys.some(k => k in object) || Object.values(object).some(hasKey)),
        keys = ['apple', 'milk', 'bread', 'coke'],
        data = { apple: { category: 'fruit' }, banana: { category: 'fruit' }, potato: { category: 'vegetable' }, dairy: { milk: { type: 'A2' } }, bakery: { bread: { type: 'brown' } }, beverage: { cold_drink: { coke: { type: 'diet' } } } },
        result = Object.fromEntries(Object
            .entries(data)
            .filter(([k, v]) => hasKey({ [k]: v }))
        );
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }