Wednesday, 13 December 2017

javascript - Check if nested key exists even if undefined






Trying to figure out what the easiest way to write a
function keyExisits that checks and arbitrarily nested key to
see if it exists in an object and is undefined, vs does not
exisit.



assume this
obj



var obj = {
a:
{
b: 1,
c: {
d: 2,
e:
undefined

}

}
}


In this
object the key a.c.e exists and is
undefined, the key a.c.f does not
exist



so



keyExists(obj, 'a.c.e') ===
true

keyExists(obj, 'a.c.f') ===
false


using
lodash/underscore is ok



** UPDATE
**



Lodash has works
exactly like this


itemprop="text">
class="normal">Answer



You can
try following




data-lang="js" data-hide="false" data-console="true"
data-babel="false">

class="snippet-code-js lang-js prettyprint-override">var obj = {a: {b:
1,c: {d: 2,e: undefined}}};

function keyExists(o, key) {

if(key.includes(".")) {
let [k, ...rest] = key.split(".");
return
keyExists(o[k], rest.join("."));
} else if(o) {

return
o.hasOwnProperty(key);
}
return
false;
}

console.log(keyExists(obj, 'a.c.e') ===
true)
console.log(keyExists(obj, 'a.c.f') ===
false)






Note:
The above code will not work if there are any dots in the
key name or you are using []
notation.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...