Code Premix

Trim all properties of an object in JavaScript

📅May 8, 2022

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.

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..!!