直接上代码了,有数据有示例,满满的干货
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script>
/*模拟数据*/
var res = {
success: true, msg: "", datas: [{ wt_code: "G02", wt_name: "大工", user_id: "001", user_name: "小明" },
{ wt_code: "G02", wt_name: "大工", user_id: "002", user_name: "小李" },
{ wt_code: "G02", wt_name: "大工", user_id: "003", user_name: "小张" },
{wt_code:"G03",wt_name:"中工",user_id:"006",user_name:"小华"},
{wt_code:"G03",wt_name:"中工",user_id:"008",user_name:"小杨"}]
}
var datajson=undefined;
/*数组转JSON*/
function arraytojson(arr1) {
if (arr1.length == 0) { return false; }
datajson={};
var key1 = "";
for (var i = 0; i < arr1.length; i++) {
key1=arr1[i]["wt_code"];
if (!datajson[key1]) {
datajson[key1] = { userList: [], name: arr1[i]["wt_name"] };
}
datajson[key1]["userList"].push({ user_id: arr1[i]["user_id"], user_name: arr1[i]["user_name"] });
}
}
/*显示转后的JSON*/
function showJson() {
if (datajson==undefined){
arraytojson(res.datas);
}
document.getElementById("TextArea1").value = JSON.stringify(datajson);
}
/*取全部工种*/
function getallwt() {
if (datajson==undefined){
arraytojson(res.datas);
}
var tmpstr = "";
for (var key in datajson) {
tmpstr += key+"="+datajson[key]["name"] + ","
}
document.getElementById("TextArea1").value = tmpstr;
}
/*取指定工种对应人员*/
function getwtperson(wtcode) {
if (datajson == undefined) {
arraytojson(res.datas);
}
var tmpstr = "";
if (!datajson[wtcode]) {
document.getElementById("TextArea1").value = wtcode + "工种不存在";
return false;
}
if (datajson[wtcode]["userList"].length == 0) {
document.getElementById("TextArea1").value = datajson[name] + "不存在相关员工";
return false;
}
var userinfo = undefined;
for (var i = 0; i < datajson[wtcode]["userList"].length; i++) {
userinfo = datajson[wtcode]["userList"][i];
tmpstr += userinfo["user_id"] + "=" + userinfo["user_name"] + ",";
}
document.getElementById("TextArea1").value = tmpstr;
}
</script>
</head>
<body>
<input type="button" οnclick="showJson()" value="显示转换后的json" /><br>
<input type="button" οnclick="getallwt()" value="获取全部工种" /><br>
<input type="button" οnclick="getwtperson('G02')" value="获取全部大工员工" /><br>
<input type="button" οnclick="getwtperson('G03')" value="获取全部中工员工" /><br>
<textarea id="TextArea1" cols="20" rows="20"></textarea>
</body>
</html>