Clue Mediator

Trim string from the dynamic object in JavaScript

📅February 8, 2021

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.

String.prototype.trim()

Demo: String.trim()

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.

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: " 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..!! 🙂