Let's say I have an object:
const object = {
lvl1: {
dogs: "bark",
lvl2: {
cats: "meow",
lvl3: {
cows: "moo"
}
}
}
}
Let's say I have two arrays:
const array1 = ["lvl1", "lvl2", "cats"]
const array2 = ["lvl1", "lvl2", "lvl3", "cows"]
How do I create a function that returns the value of cats
and cows
with only the array as an input parameter?
Let's say the function is called getValue()
.
If const value1 = getValue(array1)
were called, it should be equivalent to:
const value1 = object["lvl1"]["lvl2"]["cats"]
If const value2 = getValue(array2)
were called, it should be equivalent to:
const value2 = object["lvl1"]["lvl2"]["lvl3"]["cows"]
This is my attempt so far but it's not working:
const getValue = (array) => {
let o = object;
let newObject = o;
array.forEach((key) => (o = o[key]));
return newObject ;
};