October 22, 2024
Chicago 12, Melborne City, USA
javascript

How to dynamically fetch nested json arrays keys and properties without explicitly mentioning the fields?


I have a requirement to create a nested JSON to create an issue in JIRA.

The thing is this will work for only content.content.text path. If new keys and values are added in the future, this means it will not work. I’ve tried to automate it by fetching the keys and values in the payload.

However if you look at the following snippet, you’ll see that ‘text’ is explicitly mentioned so it could create a problem in the future. I’m trying to find a way to replace the ‘text’ to be automatically fetched instead of explicitly defining the key?

 Object.keys(newItem).forEach(k => newItem[k] = (k === 'text') ? value : newItem[k]);

So how can I find it?

function assignNestedValue(obj, path, value) {
    const parts = path.split('.');
    let current = obj;

    for (let i = 0; i < parts.length; i++) {
        const part = parts[i];

        // Handle array dynamically without explicit "type" or "text"
        if (Array.isArray(current[part])) {
            if (i === parts.length - 2) {
                const lastItem = current[part][current[part].length - 1];

                // If last item has any empty string, assign value to that key
                const emptyKey = Object.keys(lastItem).find(k => lastItem[k] === "");
                if (emptyKey) {
                    lastItem[emptyKey] = value;
                } else {
                    // If no empty field, clone the structure dynamically and assign value
                    const newItem = { ...lastItem };  // Copy existing structure
                    Object.keys(newItem).forEach(k => newItem[k] = (k === 'text') ? value : newItem[k]);
                    current[part].push(newItem); // Push the new item
                }
                return;
            }

            current = current[part][current[part].length - 1]; // Move to the last item in the array
        } else if (typeof current[part] === 'undefined') {
            // Create the path if it doesn't exist
            current[part] = {};
            current = current[part];
        } else if (i === parts.length - 1) {
            current[part] = value; // Assign value to the last part
        } else {
            current = current[part];
        }
    }
}

// Example usage of the function
var jiraPayload = {
    fields: {
        project: {
            key: ""
        },
        description: {
            type: "doc",
            version: 1,
            content: [
                {
                    type: "paragraph",
                    content: [
                        {
                            type: "text",
                            text: ""
                        }
                    ]
                }
            ]
        },
        issuetype: {
            id: "10007"
        },
        priority: {
            id: "1"
        },
        summary: ""
    }
};

// Dynamically assign values

assignNestedValue(jiraPayload.fields, "description.content.content.text", "This is the new payload description");
assignNestedValue(jiraPayload.fields, "description.content.content.text", "This is the second description");
assignNestedValue(jiraPayload.fields, "description.content.content.text", "This is the third description");
assignNestedValue(jiraPayload.fields, "description.content.content.text", "This is the fourth description");
assignNestedValue(jiraPayload.fields, "summary", "uploading json");
assignNestedValue(jiraPayload.fields, "project.key", "SI");

console.log(JSON.stringify(jiraPayload, null, 2));

the output is also working as expected

{
  "fields": {
    "project": {
      "key": "SI"
    },
    "description": {
      "type": "doc",
      "version": 1,
      "content": [
        {
          "type": "paragraph",
          "content": [
            {
              "type": "text",
              "text": "This is the new payload description"
            },
            {
              "type": "text",
              "text": "This is the second description"
            },
            {
              "type": "text",
              "text": "This is the third description"
            },
            {
              "type": "text",
              "text": "This is the fourth description"
            }
          ]
        }
      ]
    },
    "issuetype": {
      "id": "10007"
    },
    "priority": {
      "id": "1"
    },
    "summary": "uploading json"
  }
}



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video