第一種
const arr = [
{
"name": "key1",
"value": "value1",
},
{
"name": "key2",
"value": "value2",
}
]
converKey(arr, keyMap) {
let tempString= JSON.stringify(arr)
for( let key in keyMap) {
let reg= `/"${key}":/g`
tempString= tempString.replace(eval(reg), '"' + keyMap[key] + '":')
}
return JSON.parse(tempString)
},
converKey(data, {'name': 'newName'}) //注意keyMap的格式
第二種
const arr = [
{
"name": "key1",
"value": "value1",
},
{
"name": "key2",
"value": "value2",
}
]
const keyMap = { //舊key到新key的映射
name: 'newName'
}
for (let i = 0; i < arr.length; i++) {
let obj = arr[i]
for (let key in obj) {
var newKey = keyMap[key]
if (newKey) {
obj[newKey] = obj[key]
delete obj[key]
}
}
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者