getIn function implementation using Array.reduce

Gets object nested property according to provided string as a roadmap.

by Konstantin Rouda

JavaScript

;(function(){
	"use strict";


let obj = { firstProp: { secondProp: { thirdProp: "third prop string value! ;)" } } };


  /*
  * Gets Object's property value according to the provided string which is used as roadmap (e.g. "foo.baz.prop")
  * @param {Object} obj - Object to get its property
  * @param {String} prop - Roadmap to the property (e.g. "foo.baz.prop")
  */
  function getIn(obj, prop) {

     return  prop.split(".").reduce(function(obj, key) {
            return obj[key];
       }, obj);

  };


/*TEST*/

const result = getIn(obj, "firstProp.secondProp.thirdProp");

document.body.textContent = "result value is: " + result;

console.log("%c result value is: " + result, "background: #ba6464; color: #fff;");

})();