4 回答

TA貢獻1876條經驗 獲得超7個贊
我真的不確定你想用你的函數做什么,mapLower但你似乎只傳遞一個參數,即對象值。
嘗試這樣的事情(不是遞歸)
var myObj = {
Name: "Paul",
Address: "27 Light Avenue"
}
const t1 = performance.now()
const newObj = Object.fromEntries(Object.entries(myObj).map(([ key, val ]) =>
[ key.toLowerCase(), val ]))
const t2 = performance.now()
console.info(newObj)
console.log(`Operation took ${t2 - t1}ms`)
這將獲取所有對象條目(鍵/值對的數組),并將它們映射到鍵小寫的新數組,然后從這些映射條目創建新對象。
如果您需要它來處理嵌套對象,您將需要使用遞歸版本
var myObj = {
Name: "Paul",
Address: {
Street: "27 Light Avenue"
}
}
// Helper function for detection objects
const isObject = obj =>
Object.prototype.toString.call(obj) === "[object Object]"
// The entry point for recursion, iterates and maps object properties
const lowerCaseObjectKeys = obj =>
Object.fromEntries(Object.entries(obj).map(objectKeyMapper))
// Converts keys to lowercase, detects object values
// and sends them off for further conversion
const objectKeyMapper = ([ key, val ]) =>
([
key.toLowerCase(),
isObject(val)
? lowerCaseObjectKeys(val)
: val
])
const t1 = performance.now()
const newObj = lowerCaseObjectKeys(myObj)
const t2 = performance.now()
console.info(newObj)
console.log(`Operation took ${t2 - t1}ms`)

TA貢獻1828條經驗 獲得超13個贊
這將解決您的問題:
var myObj = {
Name: "Paul",
Address: "27 Light Avenue"
}
let result = Object.keys(myObj).reduce((prev, current) =>
({ ...prev, [current.toLowerCase()]: myObj[current]}), {})
console.log(result)

TA貢獻1793條經驗 獲得超6個贊
var myObj = {
Name: "Paul",
Address: "27 Light Avenue"
}
Object.keys(myObj).map(key => {
if(key.toLowerCase() != key){
myObj[key.toLowerCase()] = myObj[key];
delete myObj[key];
}
});
console.log(myObj);

TA貢獻1876條經驗 獲得超6個贊
使用json-case-convertor
const jcc = require('json-case-convertor')
var myObj = {
Name: "Paul",
Address: "27 Light Avenue"
}
const lowerCase = jcc.lowerCaseKeys(myObj)
包鏈接: https: //www.npmjs.com/package/json-case-convertor
添加回答
舉報