需求场景: 在我们日常开发中,可能会遇到后台返回的key不是你想要的的,或者是不能不能拿来直接用,然后各种for、map…,多的不说了,直接贴代码;
1.代码
/**
* 转换Key
* @param obj
* @param keyMap
* @param isDeep 是否为深度
* @return
*/
const convertKey = (obj, keyMap, isDeep) => {
if (!['[object Array]', '[object Object]'].includes(Object.prototype.toString.call(obj))) {
throw new TypeError('The first argument should be either an object or an array!');
}
if (Object.prototype.toString.call(keyMap) !== '[object Object]') {
throw new TypeError('The parameter keyMap should be an object!');
}
let res = obj instanceof Array ? [] : {};
if (obj instanceof Object) {
for (let key in obj) {
let newKey = Object.keys(keyMap).includes(key) ? keyMap[key] : key;
res[newKey] = obj[key];
//是否为深度转换
if (isDeep && obj[key] instanceof Object && Object.keys(obj[key]).length) {
res[newKey] = convertKey(obj[key], keyMap, isDeep);
}
}
}
return res;
}
2.示例:
let data = {
id: '0',
pid: '',
label: '根',
children: [
{
id: '1',
pid: '0',
label: '四川',
children: [
{
id: '1-1',
pid: '1',
label: '成都'
},
]
},
{
id: '2',
pid: '0',
label: '重庆'
}
]
}
let newData = convertKey(data, {
id: 'code',
pid: 'parentId',
label: 'name',
children: 'nodes'
}, true)
小提示: 该方法是深度拷贝,如果传了第三个参数则为深度替换,否则只会替换第一层;