• Post category:JavaScript
  • Reading time:3 mins read

In this article, we will show you how to trim all properties of an 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: String.prototype.trim()

Demo: String.trim()

const cm = "   Code Premix   ";

console.log(cm.trim());
// Output: "Code Premix";

Trim string from the dynamic object

Let’s write a logic to trim the string from the dynamic/nested object. Check the following function.

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.

const obj = {
  a: " Code Premix ",
  b: " Make your code better ",
  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: "Code Premix",
  b: "Make your code better",
  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 all we have for today.
Thank you for reading. Happy Coding..!!

Leave a Reply