Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript : trim all properties of an object [duplicate]

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?

like image 782
rap-2-h Avatar asked Jul 31 '18 14:07

rap-2-h


People also ask

How do I remove all properties of an object?

Use a for..in loop to clear an object and delete all its properties. The loop will iterate over all the enumerable properties in the object. On each iteration, use the delete operator to delete the current property. Copied!

How do you delete multiple properties from an object?

Using Delete Operator This is the oldest and most used way to delete property from an object in javascript. You can simply use the delete operator to remove property from an object. If you want to delete multiple properties, you have to use the delete operator multiple times in the same function.

How do you copy properties from one object to another in JavaScript?

The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.

How do you trim an array in JavaScript?

To trim all strings in an array:Use the map() method to iterate over the array and call the trim() method on each array element. The map method will return a new array, containing only strings with the whitespace from both ends removed.


3 Answers

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).map(k => obj[k] = typeof obj[k] == 'string' ? obj[k].trim() : obj[k]);
like image 115
cнŝdk Avatar answered Oct 20 '22 16:10

cнŝdk


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));
like image 6
Alexandre Wiechers Vaz Avatar answered Oct 20 '22 16:10

Alexandre Wiechers Vaz


You can do that by looping through it.

for(var key in myObject) {
    myObject[key] = myObject[key].trim();
}
like image 1
Sookie Singh Avatar answered Oct 20 '22 18:10

Sookie Singh