Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

a shorter way to change some object values to uppercase

I have a large object and need to change some values (not all of them) to upperCase

obj.state = obj.state.toUpperCase();
obj.city = obj.city.toUpperCase();
obj.street = obj.street.toUpperCase();
obj.title = obj.title.toUpperCase();

is there a shorter way, like this:

obj(state,city,street,title).toUpperCase();  

Thanks

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can iterate through all the keys of the object and do something like this:

for (const k of Object.keys(obj)) {
  obj[k] = obj[k].toUpperCase()
}

If you only want to update some of the values, you can filter the keys:

const keys = ['state', 'city', 'street', 'title']
for (const k of Object.keys(obj).filter((k) => keys.includes(k))) {
  obj[k] = obj[k].toUpperCase()
}

You can turn it into a function to make it reusable:

function objToUpperCase(obj, keys) {
  for (const k of Object.keys(obj).filter((k) => keys.includes(k))) {
    obj[k] = obj[k].toUpperCase()
  }
  return obj
}
// to call:
objToUpperCase(obj, ['state', 'city', 'street', 'title'])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading