So i have the following JSON object:
var myObj = {
Name: "Paul",
Address: "27 Light Avenue"
}
and I want to convert its keys to lowercase such that i would get:
var newObj = {
name: "Paul",
address: "27 Light Avenue"
}
I tried the following:
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;
}, {})
}
But I'm getting an error saying "Uncaught TypeError: field.toLowerCase is not a function".
I'm really not sure what you were trying to do there with your mapLower function but you only appear to be passing in one argument which is the object value.
Try something like this (not recursive)
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`)
This takes all the object entries (an array of key / value pairs) and maps them to a new array with the keys lowercased before creating a new object from those mapped entries.
If you need this to handle nested objects, you'll want to use a recursive version
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`)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With