EN
JavaScript - the best way to turn all object keys of to lower case?
1
answers
0
points
What is the best way to turn all object keys of to lower case?
For example, when I have object like this:
var myObject = {
Key1: 1,
KEY2: 2
};
and I want to convert it to:
var myObject = {
key1: 1,
key2: 2
};
1 answer
0
points
I think the best way to do this is to use for loop to iterate over the keys and convert them into lower case.
You can use Object.keys() method to get all keys of the original object. Then using toLowerCase() method turn them into lower case and save in a new result object.
Practical example:
// ONLINE-RUNNER:browser;
var myObject = {
Key1: 1,
KEY2: 2,
};
var key;
var keys = Object.keys(myObject);
var newObject = {};
for (var i = 0; i < keys.length; ++i) {
key = keys[i];
newObject[key.toLowerCase()] = myObject[key];
}
console.log(JSON.stringify(newObject)); // { key1: 1, key2: 2 }
References
0 comments
Add comment