2

I am not so into JavaScript and I have this problem (I can solve it only using pure old JS and not third party library).

I have a JavaScript script processing a JSON object, in my script I have:

if(finalResponse.SubSpeciesInfo == null) {
    log.info("NO SUBSPECIES");
    finalResponse.SubSpeciesInfo.SubSpeciesList = [];
}

that check if this property of my original JSON object is null:

"SubSpeciesInfo": null

If this property of my JSON object is null it enter into the if block.

What I have to do here is to append the SubSpeciesList sub field that is an empty list.

But in this way it is not working, I obtain an error like:

 ERROR {org.apache.synapse.mediators.bsf.ScriptMediator} -  The script engine returned an error executing the inlined js script function mediate {org.apache.synapse.mediators.bsf.ScriptMediator}
com.sun.phobos.script.util.ExtendedScriptException: org.mozilla.javascript.EcmaError: TypeError: Cannot set property "SubSpeciesList" of null to "org.mozilla.javascript.NativeArray@37aa205f" (<Unknown Source>#106) in <Unknown Source> at line number 106
        at com.sun.phobos.script.javascript.RhinoCompiledScript.eval(RhinoCompiledScript.java:68)

What is the problem? What am I missing? How can I fix this issue?

1 Answer 1

3

You need to assign an object with a new property for the array, because you try to use a property SubSpeciesList, which does not exist.

if (finalResponse.SubSpeciesInfo === null) {
    log.info("NO SUBSPECIES");
    finalResponse.SubSpeciesInfo = { SubSpeciesList: [] };
}

For a comparison without type coercion use better === for a strict check. Read more: Strict equality using ===

DEMO

var finalResponse = {
  SubSpeciesInfo : null 
}

if(finalResponse.SubSpeciesInfo === null) {
    console.log("NO SUBSPECIES");
    finalResponse.SubSpeciesInfo = {SubSpeciesList : []};
}

console.log(finalResponse);

Sign up to request clarification or add additional context in comments.

Comments

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.