我有一个JSON文件。我必须在此文件中读取JSON文件 WinType 是该字段中的两个值提名和赢取。我必须像alert
和1 = Win
一样将此值排列到表格中。所以我的表格显示如下
0 = Nominated
我的JSON文件是:
<html>
<body>
<TABLE BORDER=2 BORDERCOLOR=RED>
<TR>
<TD>12 Years a Slave</TD>
<TD>1</TD>
<TD>1</TD>
<TD>0</TD>
</TR>
<TR>
<TD>American Hustle</TD>
<TD>0</TD>
<TD>0</TD>
<TD>1</TD>
</TR>
<TR>
<TD>Captain Phillips</TD>
<TD>0</TD>
<TD>0</TD>
<TD>1</TD>
</TR>
</TABLE>
</body>
</html>
我试过但不能正常工作。
尝试代码
[
{
"ID":1, "Nominee":"12 Years a Slave", "WinProbability":0.00, "WinType":"Win"
},
{
"ID":2, "Nominee":"12 Years a Slave", "WinProbability":2.81, "WinType":"Win"
},
{
"ID":3, "Nominee":"12 Years a Slave", "WinProbability":0.66, "WinType":"Nominated"
},
{
"ID":1, "Nominee":"American Hustle", "WinProbability":1.62, "WinType":"Nominated"
},
{
"ID":2, "Nominee":"American Hustle", "WinProbability":0.85, "WinType":"Win"
},
{
"ID":3, "Nominee":"American Hustle", "WinProbability":0.07, "WinType":"Win"
},
{
"ID":1, "Nominee":"Captain Phillips", "WinProbability":2.70, "WinType":"Nominated"
},
{
"ID":2, "Nominee":"Captain Phillips", "WinProbability":0.00, "WinType":"Win"
},
{
"ID":3, "Nominee":"Captain Phillips", "WinProbability":1.52, "WinType":"Win"
}
]
请建议我如何解决这个问题。
答案 0 :(得分:1)
因此,您需要Nominee
之前 GROUP_BY 您的JSON数据。
var data=[{"ID":1,"Nominee":"12 Years a Slave","WinProbability":0.00,"WinType":"Win"},{"ID":2,"Nominee":"12 Years a Slave","WinProbability":2.81,"WinType":"Win"},{"ID":3,"Nominee":"12 Years a Slave","WinProbability":0.66,"WinType":"Nominated"},{"ID":1,"Nominee":"American Hustle","WinProbability":1.62,"WinType":"Nominated"},{"ID":2,"Nominee":"American Hustle","WinProbability":0.85,"WinType":"Win"},{"ID":3,"Nominee":"American Hustle","WinProbability":0.07,"WinType":"Win"},{"ID":1,"Nominee":"Captain Phillips","WinProbability":2.70,"WinType":"Nominated"},{"ID":2,"Nominee":"Captain Phillips","WinProbability":0.00,"WinType":"Win"},{"ID":3,"Nominee":"Captain Phillips","WinProbability":1.52,"WinType":"Win"}];
var groupByNominee=data.reduce(function(rv, x) {
(rv[x['Nominee']] = rv[x['Nominee']] || []).push(x);
return rv;
}, {});
var html=Object.keys(groupByNominee).map((nom)=>
`<TR>
<TD>${nom}</TD>
${groupByNominee[nom].map((item)=>`\t<TD>${(item.WinType==='Win')?1:0}</TD>`).join('\t\n')}
</TR>`
).join('\n');
$(html).appendTo('#Table');
console.log(html);
//console.log(groupByNominee);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="Table"></table>
分组data
(数组)Nominee
&amp;在groupByNominee
(数组对象)中保存输出:
---&GT;如果data=[{ID:1,Nominee:'A',WinType:'W'},{ID:2,Nominee:'B',WinType:'W'},{ID:1,Nominee:'A',WinType:'N'}]
---&GT; groupByNominee
将为={'A':[ID:1,Nominee:'A',WinType:'W'},{ID:1,Nominee:'A',WinType:'N'}],'B':[{ID:2,Nominee:'B',WinType:'W'}]}
循环遍历Nominee
(groubByNominee
)对象&amp;每次迭代
<TD>${Nominee}</TD>
<TD>WinType?0:1</TD>
html="<TD>...<TD>...</TD>...</TD>"
$(html)
&amp;包裹此字符串将其附加到Table
。