我有这个json文件,我附加到html。
"{\"Item1\":[{\"Id\":2,\"Title\":\"Support\",\"Items\":8},{\"Id\":5,\"Title\":\"Datacenter\",\"Items\":5},{\"Id\":3,\"Title\":\"Bogholderiet\",\"Items\":5},{\"Id\":8,\"Title\":\"Helpdesk\",\"Items\":4},{\"Id\":9,\"Title\":\"SLA og VIP\",\"Items\":1},{\"Id\":7,\"Title\":\"Hostmaster\",\"Items\":1}],\"Item2\":[{\"Id\":7,\"FullName\":\"p11\",\"Items\":5},{\"Id\":17,\"FullName\":\"p8\",\"Items\":3},{\"Id\":9,\"FullName\":\"p10\",\"Items\":3},{\"Id\":8,\"FullName\":\"p6\",\"Items\":3},{\"Id\":3,\"FullName\":\"p1\",\"Items\":3},{\"Id\":5,\"FullName\":\"p2\",\"Items\":2},{\"Id\":16,\"FullName\":\"p3\",\"Items\":1},{\"Id\":11,\"FullName\":\"p4\",\"Items\":1}]}"
我的问题是如何才能追加" SLA og VIP"的价值。在代码下面,我可以访问Item1的数组并将其附加到html。
if (key === 'Item1') {
value[key].forEach(function (val) {
var tbl3Row = "<tr " + (parseInt(val.TotalUnresolvedItems) > 3 ? " class='colorgul'" : "") + (parseInt(val.TotalUnresolvedItems) < 4 ? " class='colorgreen'" : "") + ">" + "<td>" + val.Title + "</td>" + "<td>" + val.TotalUnresolvedItems + "</td>" + "</tr>"
table3Rows += tbl3Row;
})
}
但现在我只是试图访问标题值&#34; SLA og VIP&#34;。这是我设法找到的公式:
parsedData.Item1[4]
我只是不知道如何在此代码中使用它:
if (key === 'Item1') {
value[key].forEach(function (val) {
var tbl3Row = "<tr " + (parseInt(val.TotalUnresolvedItems) > 3 ? " class='colorgul'" : "") + (parseInt(val.TotalUnresolvedItems) < 4 ? " class='colorgreen'" : "") + ">" + "<td>" + val.Title + "</td>" + "<td>" + val.TotalUnresolvedItems + "</td>" + "</tr>"
table3Rows += tbl3Row;
})
}
答案 0 :(得分:2)
因为它会让您过滤到您需要定位的确切对象。在你的情况下它是
{
"Id": 9,
"Title": "SLA og VIP",
"Items": 1
}
通过这种方式,您可以获得过滤后的对象的属性,例如Id, Title, Items
。
if (key === 'Item1') {
var obj = value[key].filter(function(item){
return item.Title === "SLA og VIP"
})[0];
// now use obj.Title, output: "SLA og VIP"
value[key].forEach(function(val) {
var tbl3Row = "<tr " + (parseInt(val.TotalUnresolvedItems) > 3 ? "...</tr>"
table3Rows += tbl3Row;
})
}
var json = "{\"Item1\":[{\"Id\":2,\"Title\":\"Support\",\"Items\":8},{\"Id\":5,\"Title\":\"Datacenter\",\"Items\":5},{\"Id\":3,\"Title\":\"Bogholderiet\",\"Items\":5},{\"Id\":8,\"Title\":\"Helpdesk\",\"Items\":4},{\"Id\":9,\"Title\":\"SLA og VIP\",\"Items\":1},{\"Id\":7,\"Title\":\"Hostmaster\",\"Items\":1}],\"Item2\":[{\"Id\":7,\"FullName\":\"p11\",\"Items\":5},{\"Id\":17,\"FullName\":\"p8\",\"Items\":3},{\"Id\":9,\"FullName\":\"p10\",\"Items\":3},{\"Id\":8,\"FullName\":\"p6\",\"Items\":3},{\"Id\":3,\"FullName\":\"p1\",\"Items\":3},{\"Id\":5,\"FullName\":\"p2\",\"Items\":2},{\"Id\":16,\"FullName\":\"p3\",\"Items\":1},{\"Id\":11,\"FullName\":\"p4\",\"Items\":1}]}";
var obj = JSON.parse(json)["Item1"].filter(function(item) {
return item.Title === "SLA og VIP"
})[0];
console.log(obj);
&#13;