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?
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!
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.
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.
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.
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]);
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));
You can do that by looping through it.
for(var key in myObject) {
myObject[key] = myObject[key].trim();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With