Search code examples
javascriptuppercase

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


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'])