I want to return an object containing only the keys which are passed via an array, For e.g., I have an array of keys,
const arr = ['a', 'b', 'c', 'd', 'e']
and an Object,
const obj = {
    a: {
        name: 'a',
        capital: 'A'
    },
    g: {
        name: 'g',
        capital: 'G'
    },
    b: {
        name: 'b',
        capital: 'B'
    },
    m: {
        c: {
            name: 'c',
            capital: 'C'
        }
    },
    z: {
        name: 'z',
        capital: 'Z'
    },
    n: {
        e: {
            name: 'e',
            capital: 'E'
        }
    },
    o: {
      f: {
        d: {
          name: 'd',
          capital: 'D'
        }
      }
    }
}
Now I want to return an Object which contains just the keys present in arr, 'a', 'b', 'c', 'd' and 'e', so my resultant object will be,
{
    a: {
        name: 'a',
        capital: 'A'
    },
    b: {
        name: 'b',
        capital: 'B'
    },
    c: {
        name: 'c',
        capital: 'C'
    },
    e: {
        name: 'e',
        capital: 'E'
    },
    d: {
        name: 'd',
        capital: 'D'
    }
}
Approach:
I am approaching it like as shown below, but not getting the desired result,
function fetchValueByKey(object, key, result) {
  if(typeof object !== 'object')
    return result;
  for(let objKey in object) {
    if(key.indexOf(objKey) > -1) {
      result[objKey] = object[objKey];
      console.log(result);
    } else {
      result[objKey] = fetchValueByKey(object[objKey], key, result);
      console.log(result)
    }
  }
}
console.log(fetchValueByKey(obj, arr, {}));
Please suggest me on how can I achieve this?