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
添加回答
举报