如果发现后端返回的对象中属性与对应值正好相反,推荐这样做:
let columnMap = {};
// mapInfo是后端返回的键值对相反的对象
for (let key in mapInfo) {
columnMap[mapInfo[key]] = key;
}
以下是错误示范,虽然转换成功了,代码冗余,并且后面的将英文转换成中文的部分不懂为什么不起作用:
// 利用后端返回的键值对转换需求数据的key
transCN(results, mapInfo) {
let newRe = [];
if (results instanceof Array !== true) {
for (let k in results) {
newRe[k] = results[k];
}
}
console.log(mapInfo, 'mapinfo');
let a = Object.keys(mapInfo);
let b = Object.values(mapInfo);
let newMap = {};
console.log(a, b, 'ab');
for (let k in a) {
newMap[b[k]] = a[k];
}
console.log(newMap, 'newMap');
console.log(newRe, 'newresults');
return newRe.map(enObj => {
const cnObj = {};
// const enKeys = [];
// enKeys.push(Object.keys(enObj));
const enKeys = Object.keys(enObj);
enKeys.forEach(enKey => {
if (newMap[enKey] !== undefined) {
const cnKey = newMap[enKey];
cnObj[cnKey] = enObj[enKey];
// this.$set(cnObj, 'cnKey', enObj[enKey]);
} else {
cnObj[enKey] = newMap[enKey];
}
});
return cnObj;
});
搭配我之前写的一篇中英文key值转换的博客使用,效果不错
? http://t.csdn.cn/71nV0
|