0

Write a function that takes a object and a string, which represents an object lookup path, for example "something1.something2". The function should return the value on the specific path. Example:

const lookup = (obj, path) => {....}
const obj = { something1: { something2: "Mouse", something3: 'Cat' } };
const path = 'something1.something2'
console.log(lookup(obj, path));

Result: 'Mouse'

Ismail Beg
  • 27
  • 4

1 Answers1

1

You can use split and then reference the property dynamically using square brackets

const lookup = (obj, path) => {
    const paths = path.split('.');
    return obj[paths[0]][paths[1]];
}

const obj = { something1: { something2: "Mouse", something3: 'Cat' } };
const path = 'something1.something2'

console.log(lookup(obj, path));
Ran Turner
  • 14,906
  • 5
  • 47
  • 53