将 JSON 对象键转换为小写

所以我有以下 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;

    }, {})

}

但我收到一条错误消息“Uncaught TypeError: field.toLowerCase is not a function”。


ibeautiful
浏览 195回答 4
4回答

幕布斯6054654

我真的不确定你想用你的函数做什么,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 objectsconst isObject = obj =>   Object.prototype.toString.call(obj) === "[object Object]"// The entry point for recursion, iterates and maps object propertiesconst lowerCaseObjectKeys = obj =>  Object.fromEntries(Object.entries(obj).map(objectKeyMapper))  // Converts keys to lowercase, detects object values// and sends them off for further conversionconst 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`)

慕田峪7331174

这将解决您的问题:var myObj = {   Name: "Paul",   Address: "27 Light Avenue"}let result = Object.keys(myObj).reduce((prev, current) => ({ ...prev, [current.toLowerCase()]: myObj[current]}), {})console.log(result)

摇曳的蔷薇

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);

HUX布斯

使用json-case-convertorconst 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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript