I think you should never use naive boolean conversion for such things because JS has at least 6 falsy types which can be used as regular values. This function you showed, gives you false positive result when you try extract that kind of values:
Instead of naive boolean conversions to check if object property exists always use .hasOwnProperty.👍 As a possible solution for your needs (return some defaults if path is incorrect) you can use symbols:
constNOT_FOUND_SYMBOL=Symbol('function:getProperty:notFound')functiongetProperty(obj,path,defaultValue='',pathDelimiter='.'){constpathValue=path.split(pathDelimiter).reduce((prev,curr)=>{// when not found we don't need to go deeper, kind of early exitreturn(prev!==NOT_FOUND_SYMBOL&&prev.hasOwnProperty(curr))?prev[curr]:NOT_FOUND_SYMBOL},obj)returnpathValue!==NOT_FOUND_SYMBOL?pathValue:defaultValue}constobj={a:{b:{c1:null,c2:false,c3:NaN,c4:'',c5:0,c6:undefined,c7:`It's ok`}}}console.log(getProperty(obj,'a.b.c0','Path is incorrect'))// 'Path is incorrect'console.log(getProperty(obj,'a.b.c1','Path is incorrect'))// nullconsole.log(getProperty(obj,'a.b.c2','Path is incorrect'))// falseconsole.log(getProperty(obj,'a.b.c3','Path is incorrect'))// NaNconsole.log(getProperty(obj,'a.b.c4','Path is incorrect'))// ''console.log(getProperty(obj,'a.b.c5','Path is incorrect'))// 0console.log(getProperty(obj,'a.b.c6','Path is incorrect'))// undefinedconsole.log(getProperty(obj,'a.b.c7','Path is incorrect'))// "It's ok"
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
I think you should never use naive boolean conversion for such things because JS has at least 6 falsy types which can be used as regular values. This function you showed, gives you false positive result when you try extract that kind of values:
Instead of naive boolean conversions to check if object property exists always use
.hasOwnProperty
.👍 As a possible solution for your needs (return some defaults if path is incorrect) you can use symbols: