23

Is there a way to trim all properties of an object? In other words, can I change that:

{a: ' a', b: 'b ', c: ' c '}

To this:

{a: 'a', b: 'b', c: 'c'}

It seems I can't map an object, so how can I apply a function to all properties an get the object back?

3
  • 2
    While that doesn't answer the exact, narrow, question posed; I would say that it should be very easy to get to a solution following the answer posted there. Commented Jul 31, 2018 at 14:48
  • dose it need to be deep also? Commented Jul 31, 2018 at 14:48
  • think this might be the closest thing to map an deep object JSON.stringify(obj, (k, v) => typeof v === 'string' ? v.trim() : v) Commented Jul 31, 2018 at 15:04

5 Answers 5

31

You can use Object.keys() method to iterate the object properties and update its values:

Object.keys(obj).forEach(k => obj[k] = obj[k].trim());

Demo:

var obj = {
  a: ' a',
  b: 'b ',
  c: ' c '
};

Object.keys(obj).forEach(k => obj[k] = obj[k].trim());
console.log(obj);

Edit:

If your object values can be of other data types(not only strings), you can add a check to avoid calling .trim() on non strings.

Object.keys(obj).forEach(k => obj[k] = typeof obj[k] == 'string' ? obj[k].trim() : obj[k]); 

var obj = {
  a: ' a',
  b: 'b ',
  c: ' c ',
  d: 500
};

Object.keys(obj).forEach(k => obj[k] = typeof obj[k] == 'string' ? obj[k].trim() : obj[k]);

console.log(obj);

Sign up to request clarification or add additional context in comments.

9 Comments

forEach would be preferable over map.
@photo Why would it be? .map is designed for such things.
Because map is used to return a new transformed array. Here we're just need to loop through and modify the obj.
This don't work if object contains object attributes
@pymarco I observe that .map is faster than .forEach, make me correct if I am wrong.
|
7

You can use Object.keys to reduce and trim the values, it'd look something like this:

function trimObjValues(obj) {
  return Object.keys(obj).reduce((acc, curr) => {
    acc[curr] = obj[curr].trim()
    return acc;
  }, {});
}


const ex = {a: ' a', b: ' b', c: ' c'};
console.log(trimObjValues(ex));

Comments

4

You can do that by looping through it.

for(var key in myObject) {
    myObject[key] = myObject[key].trim();
}

2 Comments

I think you need to watch out for this because for...in will go up the prototype chain and iterate over all those properties too
This can fail with on non-string objects without a trim function. Add a sanity check if (typeof parsed_pg_request[key] == 'string') {}
1

You can use a use reduce to create an object with the values you're looking for:

const test = {a: ' a', b: 'b ', c: ' c '}
const trimAllValues = input => Object.keys(input)
  .reduce((prev, next) =>
    Object.assign(prev, {
      [next]: test[next].replace(/\s+/g, '')
    }), {});
  
const result = trimAllValues(test)
console.log(result)

Lodash's mapValues will be more performant and have better browser support. You can either use lodash, or alternatively have a look at their source and implement the same:

function mapValue(object, iteratee) {
  object = Object(object)
  const result = {}

  Object.keys(object).forEach((key) => {
    result[key] = iteratee(object[key], key, object)
  })
  return result
}

Comments

0
const object1 = {
  a: ' somestring',
  b: ' a',
  c: 'a '
};

const newVals = Object.values(object1).map(val => val.trim());
console.log(newVals); //["somestring", "a", "a"]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.