1

I'm trying to write a function that trims all the values on each value on an object. It is working correctly however when someone adds a few spaces, it is getting saved as "", however I need it to save as "null" In the example above, I need the email field to come back as null when someone adds a input of " ", however it is coming back as ""

contact: {
  firstName: "John"
  lastName: "Smith"
  homePhone: null
  email: ""
}

Object.keys(contact).forEach(
  k =>
(contact[k] =
  typeof contact[k] == 'string'
    ? contact[k].trim()
    : contact[k])
)
1
  • 1
    ? (contact[k].trim() ? contact[k].trim() : null) or ? (contact[k].trim() || null) Commented Nov 17, 2020 at 5:00

1 Answer 1

3

First check it's a string, and if so trim it, and return the trimmed string if it still has length > 0.

let tidy = x => {
    if (typeof x === "string") {
        x = x.trim();
        if (x.length > 0) {
            return x;
        } else {
            return null;
        }
    } 
    return x;
};
Object.keys(contact).forEach(k => contact[k] = tidy(contact[k]));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.