Trim string from the dynamic object in JavaScript
In this short article, we will show you how to trim string from the dynamic object in JavaScript.
Sometimes we may need to remove the whitespace from the both ends of a string from the dynamic/nested objects or arrays. So here we will show an effective way to trim()
string from the whole object in JavaScript.
You will find the more information about the trim() method.
Demo: String.trim()
1 2 3 4 | const cm = " Clue Mediator "; console.log(cm.trim()); // Output: "Clue Mediator"; |
Trim string from the dynamic object
Let’s write a logic to trim the string from the dynamic/nested object. Check the following function.
1 2 3 4 5 6 7 8 9 10 11 12 | const getTrimmedData = obj => { if (obj && typeof obj === "object") { Object.keys(obj).map(key => { if (typeof obj[key] === "object") { getTrimmedData(obj[key]); } else if (typeof obj[key] === "string") { obj[key] = obj[key].trim(); } }); } return obj; }; |
Use the following object to test the function and check the output.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | const obj = { a: " Clue Mediator ", b: " The way to write your code ", c: { c1: " React ", c2: " JavaScript" }, d: ["1", " 2 ", "3 "], e: [ { e1: " Node.js ", e2: " PHP" }, { e1: " Next.js ", e2: " Git" } ], f: [ [" 1", "2", 3, " 4 "], { f1: " Follow us!" } ], g: 100, h: null, i: undefined, j: true }; getTrimmedData(obj); /* Output: { a: "Clue Mediator", b: "The way to write your code", c: { c1: "React", c2: "JavaScript" }, d: ["1", "2", "3"], e: [ { e1: "Node.js", e2: "PHP" }, { e1: "Next.js", e2: "Git" } ], f: [ ["1", "2", 3, "4"], { f1: "Follow us!" } ], g: 100, h: null, i: undefined, j: true } */ |
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂