Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript how to check if a property is missing in a json

i'm having some trouble in finding a way to check if in a parsed json object is present a property. For example in my js i have this line of code:

jsonArray = JSON.parse(jsonResponse)

I wanna check if in the jsonArray object there is the property media.

For example if my json look like this one:

Object0 {hashtags: Array[0], 
         symbols: Array[0],
         user_mentions: Array[1], 
         urls: Array[0]}
Object1 {hashtags: Array[1], 
        symbols: Array[0], 
        user_mentions: Array[0],
        urls: Array[1], 
        media: Array[1]}

i wanna check if Object0 has property media and if Object1 has property media.

Thank's

like image 646
pool Avatar asked Jan 08 '23 05:01

pool


1 Answers

You can use hasOwnProperty:

if (Object0.hasOwnProperty('media')) {
    // Object0.media
}

Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

The hasOwnProperty() method returns a boolean indicating whether the object has the specified property. Every object descended from Object inherits the hasOwnProperty method. This method can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check down the object's prototype chain.

like image 116
Tushar Avatar answered Jan 10 '23 19:01

Tushar