-1

I just want to know how can I check if a key inside a JSON exist or not

In my json file I have:

"repositories": {
"toto": {
  "tata": "https://***",
  //"titi": "***"  
  // here titi not exist
 }
},

In my script I'm doing:

 else if (type === "toto") {
        const totoURi = repositories.toto.tata;
        const titi = repositories.tgz.titi;   // here titi exist so no problem
        // but in another case how can I check variable when he not exist 

        const url =
            totoURi +
            titi +
            "." +
            type;
}
  • 2
    Duplicate of [How do I check if an object has a specific property in JavaScript?](https://stackoverflow.com/questions/135448/how-do-i-check-if-an-object-has-a-specific-property-in-javascript) – esqew Aug 07 '20 at 14:56
  • Also note you have a javascript object not JSON: https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation – Jamiec Aug 07 '20 at 14:56
  • @Jamiec (is wrapped in `{}` which I think it is...) that's a completely valid JSON, and BTW- yes JSON means exactly JavaScript Object Notation, so we can stop with the fuss. - Unless it's really invalid. – Roko C. Buljan Aug 07 '20 at 14:58
  • @RokoC.Buljan it's in a Javascript context, not contained within a string. Its not JSON. `{"foo":42}` is Javascript. `'{"foo",42}'` is JSON. There is a difference, just because one is a subset of the other does _not_ make the the same thing. – Jamiec Aug 07 '20 at 15:03
  • @Roko that's not a json, you can't determine if it is a json or object because the full code isn't shown, a json must be stringified. And also note **JSON** is a string not an object. – Fritzdultimate Aug 07 '20 at 15:05

1 Answers1

0

Ciao, you could use hasOwnProperty function like this example:

const data = {"repositories": {
"toto": {
  "tata": "https://***",
  //"titi": "***"  
  // here titi not exist
 }
}};

console.log(data.repositories.toto.hasOwnProperty("tata"))

console.log(data.repositories.toto.hasOwnProperty("titi"))
Giovanni Esposito
  • 10,696
  • 1
  • 14
  • 30