JSFiddle - React, Tailwind, and code Playground
JavaScript
/**
* @function getValueByNs
* @param {*} obj
* @param {string} path
* @param {*} defaultValue
* @return {*}
* @description return value from object by string path or default value
* Examples:
* obj = [1,2,3]; getValueByNs(obj, 'length', 0) will return 3
* obj = {0: 'a', 1: 'b', 2: 'c'}; getValueByNs(obj, 'length') will return ''
* obj = {0: 'a', 1: 'b', 2: 'c'}; getValueByNs(obj, 'length', 0) will return 0
* obj = {0: 'a', 1: 'b', 2: 'c'}; getValueByNs(obj, '1') will return 'b'
* obj = {0: 'a', 'x': {'a':5}, 2: 'c'}; getValueByNs(obj, 'x.a', 0) will return 5
*/
const getValueByNs = (obj, path, defaultValue = '') => {
const keys = path.split('.');
keys.forEach(key => {
if (obj) {
obj = obj[key];
}
});
return obj || defaultValue;
}