亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將 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 關注
  • 273 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號