后台返回数据:result
{"code":null,"
data":[{"id":"DE61B8FD-EC8C-F5D1-6CCC-1A0385DBF517",
"code":"role_002","name":"用车申请人","description":null,
"prjCode":"govCarMgr","disable":"0"},
{"id":"47B6EF21-41BC-D6AC-CBB7-EF503013A8F5","code":"role_003","name":"审批人",
"description":null,"prjCode":"govCarMgr","disable":"0"},
{"id":"8C2453F9-AE1E-431F-9D01-7C303BA4864E","code":"role_004","name":"调度员",
"description":null,"prjCode":"govCarMgr","disable":"0"},
{"id":"9EA34817-1C50-34EF-7439-639ECA8FE9B0","code":"role_001","name":"系统管理员",
"description":null,"prjCode":"govCarMgr","disable":"0"}],
"success":true,"mgs":"查询成功"}
result.data:
[{"id":"DE61B8FD-EC8C-F5D1-6CCC-1A0385DBF517","code":"role_002","name":"用车申请人",
"description":null,"prjCode":"govCarMgr","disable":"0"},{"id":"47B6EF21-41BC-D6AC-CBB7-EF503013A8F5","code":"role_003","name":"审批人","description":null,"prjCode":"govCarMgr","disable":"0"},{"id":"8C2453F9-AE1E-431F-9D01-7C303BA4864E","code":"role_004","name":"调度员","description":null,"prjCode":"govCarMgr","disable":"0"},{"id":"9EA34817-1C50-34EF-7439-639ECA8FE9B0","code":"role_001","name":"系统管理员",
"description":null,"prjCode":"govCarMgr","disable":"0"}]
循环将记录中key对应的value取出,放入role对象中
for(var i in result.data){
var obj=result.data[i].code;
role[obj]=result.data[i].name;
}
console.log(JSON.stringify(role))
输出结果:
{“role_002”:”用车申请人”,”role_003”:”审批人”,”role_004”:”调度员”,”role_001”:”系统管理员”}
var ROLE={“role_002”:”用车申请人”,”role_003”:”审批人”,”role_004”:”调度员”,”role_001”:”系统管理员”};
通过以下方法就可以成功通过key得到value
function getRoleValue(key){
var rolevalue={};
rolevalue=ROLE[key];
return dv;
}
注意:当key为中文如果后台返回中文编码和页面的文字编码不一样的话,ROLE[key]为undefined,就不能通过这种方法找到,用中文作为key容易出现问题,所以要避免用中文作为key