3000 3000 - 2 months ago 6
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):

{"a":{"b":{"c":"","d":"t"}}}


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

I appreciate any help.

Answer

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;
console.log(result)

Or you can check for key with hasOwnProperty

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

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

Comments