Reputation: 2117
I'm trying to check if json[0]['DATA']['name'][0]['DATA']['first_0'] exists or not when in some instances json[0]['DATA']['name'] contains nothing.
I can check json[0]['DATA']['name'] using
if (json[0]['DATA']['name'] == '') {
// DOES NOT EXIST
}
however
if (json[0]['DATA']['name'][0]['DATA']['first_0'] == '' || json[0]['DATA']['name'][0]['DATA']['first_0'] == 'undefined') {
// DOES NOT EXIST
}
returns json[0]['DATA']['name'][0]['DATA'] is null or not an object. I understand this is because the array 'name' doesn't contain anything in this case, but in other cases first_0 does exist and json[0]['DATA']['name'] does return a value.
Is there a way that I can check json[0]['DATA']['name'][0]['DATA']['first_0'] directly without having to do the following?
if (json[0]['DATA']['name'] == '') {
if (json[0]['DATA']['name'][0]['DATA']['first_0'] != 'undefined') {
// OBJECT EXISTS
}
}
Upvotes: 0
Views: 4394
Reputation: 38420
To check if a property is set you can just say
if (json[0]['DATA']['name']) {
...
}
unless that object explicitly can contain 0
(zero) or ''
(an empty string) because they also evaluate to false
. In that case you need to explicitly check for undefined
if (typeof(json[0]['DATA']['name']) !== "undefined") {
...
}
If you have several such chains of object property references a utility function such as:
function readProperty(json, properties) {
// Breaks if properties isn't an array of at least 1 item
if (properties.length == 1)
return json[properties[0]];
else {
var property = properties.shift();
if (typeof(json[property]) !== "undefined")
return readProperty(json[property], properties);
else
return; // returns undefined
}
}
var myValue = readProperty(json, [0, 'DATA', 'name', 0, 'DATA', 'first_0']);
if (typeof(myValue) !== 'undefined') {
// Do something with myValue
}
Upvotes: 4
Reputation: 11238
so you're asking if you have to check if a child exists where the parent may not exist? no, I don't believe you can do that.
edit: and just so it's not a total loss, what's with all the brackets?
json[0]['DATA']['name'][0]['DATA']['first_0']
could probably be
json[0].DATA.name[0].DATA.first_0
right?
Upvotes: 1