javascript : trim all properties of an object
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();
}