// 将arr对象中的name键改为text、userName键改为text、userList键改为chilren
// console.log(this.copyTransFunc(arr, [{ key: "name", value: "text" }, { key: "userName", value: "text" },{ key: "userList", value: "chilren" }]));
let copyTrans = function (obj, typeArr) {
let result
let toString = Object.prototype.toString
if (toString.call(obj) === '[object Array]') {
result = []
for (let i = 0; i < obj.length; i++) {
result[i] = copyTrans(obj[i], arguments[1])
}
} else if (toString.call(obj) === '[object Object]') {
result = {}
for (let _key in obj) {
if (obj.hasOwnProperty(_key)) {
let flag = 0,
_value = null
for (let j = 0; j < arguments[1].length; j++) {
if (arguments[1][j].key === _key) {
flag = 1
_value = arguments[1][j].value
}
}
if (flag) result[_value] = copyTrans(obj[_key], arguments[1])
else result[_key] = copyTrans(obj[_key], arguments[1])
}
}
} else {
return obj
}
return result
}
export default copyTrans
转载请注明:有爱前端 » js更改对象中属性名的方法