ValueOf - Get JS Object property value

Prevent JS script from failing when object property you are trying to reference is undefined

by Eugene Trounev

HTML

<h1>
Check the console <kbd>[F12]</kbd>!
</h1>
<pre>
<code>
function ValueOf(from: any, path: string, propDefault?: any): any
</code>
Returns the value of object nested propery
without failing, even when the obeject is indefined
@export
@param {*} from Object to extract the property value from
@param {string} path a string path to the property
@param {*} [propDefault] a default value to return in case any of the path asertions fail (optional)
@returns {*} returns the value of the propety, or default value
@example
<code>
const obj = {
	prop1: {
 	prop2: "test",
   props3: null
 },
 props2: [1,2,3]
}

console.log("should return 'test'", ExtractObjectProp(obj, "prop1.prop2"));
console.log("should return [1,2,3]", ExtractObjectProp(obj, "props2"));
console.log("should return 'default'", ExtractObjectProp(obj, "prop1.prop4.nothing", "default"));
console.log("should return 'null'", ExtractObjectProp(obj, "prop1.prop4.props3", "null"));
console.log("should return undefined", ExtractObjectProp(obj, "prop3.prop2.prop1"));
</code>
</pre>

TypeScript

/**
 * Returns the value of object nested propery
 * without failing, even when the obeject is indefined
 * @export
 * @param {*} from Object to extract the property value from
 * @param {string} path a string path to the property
 * @param {*} [propDefault] a default value to return in case any of the path asertions fail (optional)
 * @returns {*} returns the value of the propety, or default value
 * @example
 * const obj = {
 *	prop1: {
 *  	prop2: "test",
 *    props3: null
 *  },
 *  props2: [1,2,3]
 * }
 *
 * console.log("should return 'test'", ExtractObjectProp(obj, "prop1.prop2"));
 * console.log("should return [1,2,3]", ExtractObjectProp(obj, "props2"));
 * console.log("should return 'default'", ExtractObjectProp(obj, "prop1.prop4.nothing", "default"));
 * console.log("should return 'null'", ExtractObjectProp(obj, "prop1.prop4.props3", "null"));
 * console.log("should return undefined", ExtractObjectProp(obj, "prop3.prop2.prop1"));
 */
function ValueOf(from: any, path: string, propDefault?: any): any {
    const props = path.split(".");
    let result = from;
    for (let i = 0; i < props.length; i++) {
        if (Boolean(result) && Boolean(result[props[i]]) {
            result = result[props[i]];
        } else {
            result = propDefault;
        }
    }
    return result;
}

const obj = {
	prop1: {
  	prop2: "test",
    props3: null
  },
  props2: [1,2,3]
}

console.log("should work", ExtractObjectProp(obj, "prop1.prop2"));
console.log("should work", ExtractObjectProp(obj, "props2"));
console.log("should default", ExtractObjectProp(obj, "prop1.prop4.nothing", "default"));
console.log("should default", ExtractObjectProp(obj, "prop1.prop4.props3", "null"));
console.log("should undefined", ExtractObjectProp(obj, "prop3.prop2.prop1"));