2

I have object having string as keys and values. I want to trim all values of object in one go without need to check every index manually.

So, I have to iterate over object and will trim the value and the update value in object.

Can you share a way to iterate any object in Angulario 5.

let obj = {
  "name" => "    keshav     ",
  "prof" => "    Engineer   "
}

And I would like to this to convert into

let obj = {
  "name" => "keshav",
  "prof" => "Engineer"
}
Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149
user5258139
  • 31
  • 1
  • 3
  • This question is not Anguar(io5) specific. You must also show your attempts to resolve – Vega May 11 '18 at 06:56
  • 2
    Possible duplicate of [Trim white spaces in both Object key and value recursively](https://stackoverflow.com/questions/33510625/trim-white-spaces-in-both-object-key-and-value-recursively) – Vega May 11 '18 at 07:04

3 Answers3

4

You can use Object.entries:

Object.entries(obj).forEach(([key, value]) => obj[key] = value.trim());

This way you maintain the reference of the object

Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149
1

you have to do like this, get all the object properties and then just trim it

 const properties = Object.keys(obj );
 properties.forEach(prop=>{
   obj[prop]= obj[prop].trim();  
 });
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
0

you can us simple for as well :

for(index in obj) { 
   obj[index] = obj[index].trim();
}
Yanis-git
  • 7,737
  • 3
  • 24
  • 41