gpt4 book ai didi

javascript - 将 JSON 对象键转换为小写

转载 作者:行者123 更新时间:2023-12-05 00:55:16 24 4
gpt4 key购买 nike

所以我有以下 JSON 对象:

var myObj = {
Name: "Paul",
Address: "27 Light Avenue"
}

我想将它的键转换为小写,这样我会得到:

var newObj = {
name: "Paul",
address: "27 Light Avenue"
}

我尝试了以下方法:

var newObj = mapLower(myObj, function(field) {
return field.toLowerCase();
})

function mapLower(obj, mapFunc) {
return Object.keys(obj).reduce(function(result,key) {
result[key] = mapFunc(obj[key])
return result;
}, {})
}

但我收到一条错误消息,提示“未捕获的 TypeError:field.toLowerCase 不是函数”。

最佳答案

我真的不确定你想用 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`)

关于javascript - 将 JSON 对象键转换为小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64869036/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com