-1

I have an object which I am forming with all the input values from a form. I want to go through the object and change all the input value to lowercase before I make a post request to the backend. I want to write a function that takes that object and returns a new object with lowercase value

const obj = {name: 'Test', city: 'London'}
const modifiedObj = myFunction(obj)

modifiedObj should be:

{name: 'test', city: 'london'}
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
Prabs
  • 117
  • 2
  • 11

1 Answers1

0

You can use Object.keys to get the keys of your object, then iterate through them and access each property.


function myFunction(object){
  const newObj = {};
  cons keys = Object.keys(object);
  for(const key of keys){
    if(typeof object[key]!=="string"){
      newObject[key] = object[key];
      continue;
    }
    newObj[key] = object[key].toLowerCase();
  }
  return newObj;
}
jro
  • 900
  • 1
  • 10
  • 21
  • I just need to make little change to make sure that I call toLowerCase() only to string value – Prabs Mar 24 '19 at 11:44
  • @Prabs If it is possible that values are not strings, then certainly, your method works. Would you like me to edit that into my answer? – jro Mar 24 '19 at 11:46
  • `const toLowercase = object => { const keys = Object.keys(object); const newObject = {}; for (const key of keys) { const value = typeof object[key] === 'string'? object[key].toLowerCase(): object[key] newObject[key] = value } return newObject; };` – Prabs Mar 24 '19 at 11:49