将JSON对象的键转换为小写

3

我有以下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;
    }, {})
}

但是我收到一个错误,说“未捕获的类型错误:field.toLowerCase不是一个函数”。


有一个名为humps(https://github.com/domchristie/humps)的库,如果您想要在camelCase或PascalCase之间进行转换,则可以处理几个关键转换。 如果您知道您的键始终只有一个单词,那么您可能不需要它,但是如果您有像“first_name”或“FirstName”或“firstName”这样的键,则humps可以将所有这些规范化为相同的形状。 - mr rogers
5个回答

6

我不太确定你在尝试使用 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`)


2
这将解决您的问题:

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

let result = Object.keys(myObj).reduce((prev, current) => 
({ ...prev, [current.toLowerCase()]: myObj[current]}), {})

console.log(result)


1
这个答案是最糟糕的,它的复杂性使得它无法处理大对象。我的基准测试使用了1000个属性:laguf1.mobi的操作花费了35毫秒,Ami Hollander的操作花费了44毫秒,Phil的操作花费了131毫秒,@tsamridh86的操作花费了11838毫秒。 - Damien Garrido

1

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


到目前为止,这是我找到的最快的。 - Damien Garrido

0

0

我无法重现你的错误,但如果你想降低密钥,应该这样做:

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

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

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

console.log(newObj)

将返回 { name: 'Paul', address: '27 Light Avenue' }


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接