Languages

JavaScript - the best way to turn all object keys of to lower case?

0 points
Asked by:
Hayley-Mooney
677

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
Answered by:
Hayley-Mooney
677

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

  1. Object.keys() - JavaScript | MDN
  2. String.prototype.toLowerCase() - JavaScript | MDN
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join