为了账号安全,请及时绑定邮箱和手机立即绑定

将 JSON 对象键转换为小写

将 JSON 对象键转换为小写

ibeautiful 2023-08-10 15:48:51
所以我有以下 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”。
查看完整描述

4 回答

?
幕布斯6054654

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


查看完整回答
反对 回复 2023-08-10
?
慕田峪7331174

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)


查看完整回答
反对 回复 2023-08-10
?
摇曳的蔷薇

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


查看完整回答
反对 回复 2023-08-10
?
HUX布斯

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


查看完整回答
反对 回复 2023-08-10
  • 4 回答
  • 0 关注
  • 194 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信