0

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

provance
  • 877
  • 6
  • 10

1 Answers1

2

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'])
casraf
  • 21,085
  • 9
  • 56
  • 91
  • this will change all values, I need some of them only – provance May 19 '22 at 19:33
  • Might want to check that [Object or its prototype has a property:](https://stackoverflow.com/a/1894803/14956277) `if ('toUpperCase' in obj[k])`. – D M May 19 '22 at 19:34