0

需要遍历以下 JSON 对象以生成报告(表格结构中的表格报告)。

报告将基本上由故事列表及其相关任务状态组成。

QueryResults = {
    "Results": [
        {
            "Name" : "Tech Design",
            "State" : "Completed",
            "StoryName" : "FB Integration"
        },
        {
            "Name" : "Development",
            "State" : "In-Progress",
            "StoryName" : "FB Integration"
        },
        {
            "Name" : "QA Testing",
            "State" : "Not Started",
            "StoryName" : "FB Integration"
        },
        {
            "Name" : "Front End Development",
            "State" : "Completed",
            "StoryName" : "FB Integration"
        },
        {
            "Name" : "Tech Design",
            "State" : "Not Started",
            "StoryName" : "Twitter Integration"
        },
        {
            "Name" : "Development",
            "State" : "Not Started",
            "StoryName" : "Twitter Integration"
        }
    ]
}

要填充的 HTML:

<table>
    <tr>
        <td>StoryName</td>
        <td>TechDesign</td>
        <td>FED</td>
        <td>QA</td>
        <td>Development</td>
    </tr>
    <tr>
        <td>FB Integration</td>
        <td>Completed</td>
        <td>Completed</td>
        <td>In-Progress</td>
        <td>In-Progress</td>
    </tr>
    ......
    ......
</table>

脚本 :

for(var i=0; i < QueryResults.Results.length; i++) {
  data+= '<tr><td>' + QueryResults.Results[i].StoryName + '</td><td>' + QueryResults.Results[i].State + '</td></tr>'; 
}

// it will list down all the story name i.e. same story name multiple times

请在迭代 JSON 并在其他列中填充相应的详细信息时为我提供删除重复故事名称的指针。

4

1 回答 1

3

您不想删除重复的条目,而是希望按故事名称合并它们。

var stories = {};
for (var i=0; i<QueryResults.Results.length; i++) {
    var result = QueryResults.Results[i],
        name = result.StoryName
    if (!(name in stories))
        stories[name] = {};
    stories[name][result.Name] = result.State;
}
/* console.log(stories):
{
    "FB Integration":{"Tech Design":"Completed","Development":"In-Progress","QA Testing":"Not Started","Front End Development":"Completed"},
    "Twitter Integration":{"Tech Design":"Not Started","Development":"Not Started"}
} */

现在您可以从中构建一个表。

var keys = [];
for (var i=0; i<QueryResults.Results.length; i++) {
    var n = QueryResults.Results[i].Name;
    if (keys.indexOf(n) == -1)
         keys.push(n);
}
var data = "<table><tr><th>Story Name</th>";
for (var i=0; i<keys.length; i++)
    data += "<th>"+keys[i]+"</th>";
data += "</tr>";
for (var storyname in stories) {
    data += "<tr><th>"+storyname+"</th>";
    for (var i=0; i<keys.length; i++)
        data += "<td>"+(stories[storyname][keys[i]] || "n.a.")+"</td>";
    data += "</tr>";
}
data += "</table>";

如果您想确保特定顺序或使用自定义表头,您当然也可以使用静态keys数组:

var keys = ["Tech Design","Front End Development","QA Testing","Development"];
var data = "<table><tr><td>StoryName</td><td>TechDesign</td><td>FED</td><td>QA</td><td>Development</td></tr>";
for (storyname in stories) {
…
于 2013-07-16T14:26:26.760 回答