使用jQuery遍历嵌套JSON获取Issue首个Component的Name
Hey there! Let's get this sorted for you. Since you confirmed each issue's components array always contains exactly one element, grabbing that component's name should be simple—let's adjust your code to make it work.
The Core Fix
Your code was on the right track with iterating over data_add.issues; you just need to correctly access the first (and only) element in the components array, then pull its name property. Here's the completed version:
$(document).ready(function() { $.getJSON("./json/PI-19/taxonomyAddedAfterSprintStart.19.3.json", function(data_add) { var jira_data_add = ''; $.each(data_add.issues, function(key, val){ // Access the first component's name directly const componentName = val.components[0].name; console.log(componentName); // This should log "KBR" as expected // If you're building output content, you can append it like this: jira_data_add += `<div>Issue ${key + 1}: Component - ${componentName}</div>`; }); // Finally, insert the compiled content into your page (adjust the selector as needed) $('#jira-content').html(jira_data_add); }); });
Optional Safety Check
Even though you said the components array will always have one element, adding a quick check can prevent errors if something unexpected happens (like a malformed entry in the JSON):
$.each(data_add.issues, function(key, val){ let componentName = 'No component found'; // Verify components exists and has at least one element if (val.components && val.components.length > 0) { componentName = val.components[0].name; } console.log(`Issue ${key + 1}: ${componentName}`); });
This way, you'll get a fallback message instead of a JavaScript error if the data doesn't match your expectations.
内容的提问来源于stack exchange,提问作者Rich Meadows

