0

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
    }
}

2 Answers 2

4

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
}
Sign up to request clarification or add additional context in comments.

Comments

1

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?

1 Comment

Yep, that's what I'm asking. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.