javascriptmirth

Mirth JSON Object Population


I need help trying to populate this object structure.

{
   "fields": {
       "project":
       {
          "key": "TEST"
       },
       "summary": "Who seeks a faultless friend RESTs friendless.",
       "description": "Creating an issue and setting time tracking fields",
       "issuetype": {
          "name": "Bug"
        }
    }
}

I tried this but it doesn't like it. I get "Cannot read property project from undefined".

var newObject = {code:{}};
newObject['fields']['project']['key']="X";
newObject['fields']['summary']= "Y";
newObject['fields']['issuetype']['name'] = "Z";
newObject['fields']['assignee']['name'] = "A";
newObject['fields']['priority']['name'] = "B";

Solution

  • "Cannot read property project from undefined" means that you are trying to access a value from a property that does not exist. In your context, javascript is trying to access 'project', but the property preceding project, aka newObject['fields'], is undefined.

    You are trying to populate your object a little to fast hehe. You have to create each property before adding any keys & values. In other words, go step by step.

    There is a couple ways to address this problem, here are two:

    Solution #1

    Add properties when you create newObject, like so:

     var newObject = {
        fields: {
        project: {},
        issuetype: {},
        assignee: {},
        priority: {}
      }
    };
    

    And then proceed with the same code you had & populate keys inside each properties.

    Solution #2

    var newObject = {code:{}};
    newObject.fields = {}; // First create the property
    newObject['fields']['project'] = {}; // Then add new keys & values
    newObject['fields']['project']['key']= "X";
    
    newObject.fields.issuetype = {}; // First create the proprerty issuetype
    newObject.fields.assignee= {}; // First create the proprerty assignee
    newObject.fields.priority= {}; // First create the proprerty priority
    newObject['fields']['issuetype']['name'] = "Z"; // Then add new keys & values
    newObject['fields']['assignee']['name'] = "A"; // ...
    newObject['fields']['priority']['name'] = "B"; // ...