最近在写老项目,后端是直接返回Json数据的,今天遇到了一个问题,前端form,只能有一个key比如我form里面套了一个table,但是里面还需要套两个table,这两table,值是一样的,比如两个都有联络人liaison,但是这样写,就一个也赋值不了,所以需要改名字,想了很久,用了replace,但是replace都是String的,搞了很久才发现是Object的,而且是老项目不能用新的写法,必须functionxxxx才行,我说怎么运行到哪里就报错,把代码分享出来,下面还有新老写法都有
function selectSingleDeptID1(){
var sysDeptId = document.getElementById("depLow1").value;
if(sysDeptId != ""){//编辑
var url = contextPath + "/organizationController/getBySysDeptId.action";
var json = tools.requestJsonRs(url,{sysDeptId:sysDeptId});
if(json.rtState){
var data = json.rtData;
const mapObj = {
responsibleLeadership: "responsibleLeadership1",
liaison: "liaison1",
liaisonPhone: "liaisonPhone1",
};
function replaceKey(data, keyMap) {
let str = JSON.stringify(data);
let keyStr = Object.keys(keyMap).join("|");
let reg = new RegExp("\"(" + keyStr + ")\":", "g");
str = str.replace(reg, (matched, $1) => "\"" + keyMap[$1] + "\":");
return JSON.parse(str);
}
const o = replaceKey(data, mapObj);
if(o.id){
bindJsonObj2Easyui(o,"form1");
}
}else{
$.MsgBox.Alert_auto(json.rtMsrg);
}
}
var id = $("#id").val();
/*initPersonGrid(id);*/
}
下面来个demo
假设一个object的如下:
const obj={
_id: 424228910,
user_name:'仵航'
}
需求希望把这个object变成如下:
const obj={
id: 424228910,
userName:'仵航'
}
方法一:
const mapObj = {
_id: "id",
user_name: "userName",
};
function replaceKey(obj, keyMap) {
let str = JSON.stringify(obj);
let keyStr = Object.keys(keyMap).join("|");
let reg = new RegExp("\"(" + keyStr + ")\":", "g");
str = str.replace(reg, (matched, $1) => "\"" + keyMap[$1] + "\":");
return JSON.parse(str);
}
const o = replaceKey(obj, mapObj);
方法二:
const mapObj = {
_id: "id",
user_name: "userName",
};
const newObj = Object.fromEntries(Object.entries(obj).map(([k, v]) => [mapObj[k]||k, v]))
拿走不谢