0

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 ;
  };
mbojko
  • 13,503
  • 1
  • 16
  • 26
Jake
  • 3,865
  • 5
  • 25
  • 58
  • 1
    The linked question's answers start with a string, but then they split it into an array, at which point they apply to the above. – T.J. Crowder May 05 '19 at 09:54
  • 1
    You are almost there. Inside `getValue`, do `return o` instead of `return newObject` – adiga May 05 '19 at 09:57
  • Yeah you're right. I also needed to set `o` to `let o = { ...object }`. Thanks for the help! – Jake May 05 '19 at 10:03
  • Since you are reassigning `o = o[key]`, it will just change `o` and not the original `object`. So, cloning is not really required. – adiga May 05 '19 at 10:18

0 Answers0