3000 3000 - 9 months ago 34
Javascript Question

Check for the existence of a key in a JSON coming from server

In pure JavaScript I want to check for the existence of a JSON key. The JSON is in the following form (I simplify):


I must check for the existence of "c" (
) because under some circumstances the server returns a JSON containing "d" but not "c".

I appreciate any help.


After you parse json with JSON.parse() you can use Object.keys() and indexOf()

var data = {"a":{"b":{"c":"","d":"t"}}}
var result = Object.keys(data.a.b).indexOf('c') != -1;

Or you can check for key with hasOwnProperty

var data = {"a":{"b":{"c":"","d":"t"}}}

if(data.a.b.hasOwnProperty('c')) console.log('True')