In JavaScript, how can I return a boolean indicating whether a key is present in a JSON object?

I have a pretty simple question: in Javascript, can I return a boolean value (if found in JSON), and not the actual value?

Example:

 var myJSON = { 
                  "foo" : "bar",
                  "bar" : "foo"
              };
 var keyToLookFor = "foo";
 var found = myJSON[keyToLookFor];

 if (found) {
     // I know I can test if the string exists in the if
 }
  // but is there a way I could just return something like:
 return found;
 // instead of testing found in the if statement and then returning true?
+3
source share
3 answers

You need to check the 'in' keyword:

if (keyToLookFor in myJSON) {
}

To simplify it, you can use:

return keyToLookFor in myJSON;
+8
source

An operator incan tell you if a key exists in an object or any of the objects in the prototype chain. A function hasOwnPropertycan tell you if this key exists in the object itself (not in any of the objects in the prototype chain).

if ("foo" in obj) {
   // `obj` or an ancestor has a key called "foo"
}

if (obj.hasOwnProperty("foo")) {
   // `obj` has a key called "foo"
}

, , Object ({} = > new Object()), . , , , , :

var a = [1, 2, 3, 4];
a.foo = "testing";

alert("push" in a);              // 1. alerts "true"
alert(a.hasOwnProperty("push")); // 2. alerts "false"
alert("foo" in a);               // 3. alerts "true"
alert(a.hasOwnProperty("foo"));  // 4. alerts "true"

# 1 true, push Array.prototype ( , ). # 2 , push , . # 3 # 4 true, foo .

JSON, Javascript Object Literal Notation, JSON . ( " " ) . , ( ) . {} JSON, , , , "undefined" .: -)

+3

, false, found .. , :)

( ), :

return !!found;

.

:

return keyToLookFor in myJSON;
0

Source: https://habr.com/ru/post/1742306/


All Articles