4 回答

TA貢獻(xiàn)1876條經(jīng)驗(yàn) 獲得超7個(gè)贊
我真的不確定你想用你的函數(shù)做什么,mapLower但你似乎只傳遞一個(gè)參數(shù),即對(duì)象值。
嘗試這樣的事情(不是遞歸)
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`)
這將獲取所有對(duì)象條目(鍵/值對(duì)的數(shù)組),并將它們映射到鍵小寫的新數(shù)組,然后從這些映射條目創(chuàng)建新對(duì)象。
如果您需要它來(lái)處理嵌套對(duì)象,您將需要使用遞歸版本
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貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超13個(gè)贊
這將解決您的問(wèn)題:
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貢獻(xiàn)1793條經(jīng)驗(yàn) 獲得超6個(gè)贊
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貢獻(xiàn)1876條經(jīng)驗(yàn) 獲得超6個(gè)贊
使用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
添加回答
舉報(bào)