Search code examples
javascriptmirthmirth-connect

how do i check if attribute from XML tag is undefined JavaScript (Mirth Connect)


I want to check if attribute in XML tag is present or not.

here is the sample xml tag: <value @code="">

i Want to check following conditions..

  1. if tag is present.
  2. if @code is present.
  3. if @code is null.

currently I am checking condition as below:

if(msg['value'])
{
  hasValue='true';
  
  if(msg['value']['@code'])
  {
      hasCode='true';
  }else
  {
    hasCode='false';
  }
  
}

but this condition returns hasValue flag always true. Even if @code is missing/undefined.

Is there a way to check if @code is undefined/missing?


Solution

  • You can use hasOwnProperty() to check for the existence of an element or attribute, and you can use .toString() to check whether the attribute value is empty or not.

    if(msg.hasOwnProperty('value')) {
      hasValue='true';
    
      if(msg.value.hasOwnProperty('@code') && msg.value['@code'].toString()) {
        hasCode='true';
      } else {
        hasCode='false';
      }
    }