How to implement a function that outputs the value of an object?

  • 0
    Hello. Tell me how you can write a function using reduce inside that takes 2 parameters getValueObj (obj, path) (Object and path to it) and outputs the value of the object.
    obj = {
      s:2,
      d:4,
      g: {t:4}
    }
    getValueObj(obj, g.t) //4
    JavaScript Anonymous, May 1, 2020

  • 1 Answers
  • 0
    obj = {
    s:2,
    d:4,
    g: {t:4}
    };

    const getValueObj = (obj, path) => {
    return path.split('.').reduce((acc, key) => acc[key], obj);
    }

    getValueObj(obj, 'g.t') //4
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!