I have a serializable JavaScript object such as
{
a: 'hello ',
b: [],
c: 5,
d: {
e: ' world ';
},
}
and I would like to create a JavaScript object similar to the original object except that every string value has leading and trailing whitespace removed:
{
a: 'hello',
b: [],
c: 5,
d: {
e: 'world';
},
}
How can I do this?
I have a serializable JavaScript object such as
{
a: 'hello ',
b: [],
c: 5,
d: {
e: ' world ';
},
}
and I would like to create a JavaScript object similar to the original object except that every string value has leading and trailing whitespace removed:
{
a: 'hello',
b: [],
c: 5,
d: {
e: 'world';
},
}
How can I do this?
Share Improve this question asked Apr 3, 2019 at 1:03 markmark 5,0708 gold badges38 silver badges50 bronze badges 04 Answers
Reset to default 9JSON.stringify
has a replacer
parameter that we can use
const replacer = (key, value) => {
if (typeof value === 'string') {
return value.trim();
}
return value;
};
const trimmedObj = JSON.parse(JSON.stringify(obj, replacer));
Note that JSON does not have undefined
values, so any keys with undefined values will be stripped out of the resulting object. You may use null
in place of undefined
if you wish to preserve these values and if null
is suitable for your purposes.
const replacer = (key, value) => {
if (typeof value === 'string') {
return value.trim();
}
if (value === undefined) {
// JSON doesn't have undefined
return null;
}
return value;
};
You can recursively trim the object like so (note that my solution will mutate your initial object):
let obj = {
a: 'hello ',
b: [" foo ", " bar"],
c: 5,
d: {
e: ' world '
}
};
trimAll = obj => {
Object.keys(obj).map(key => {
if (typeof obj[key] === 'string') {
obj[key] = obj[key].trim();
} else {
trimAll(obj[key]);
}
});
}
trimAll(obj);
console.log(obj);
Here is my recursive function to handle this:
let x = {
a: 'hello ',
b: [' hi ', 'we '],
c: 5,
d: {
e: ' world '
},
};
function trimRecursively(value) {
if (Array.isArray(value)) {
return value.reduce((all, item) => {
all.push(trimRecursively(item));
return all;
}, []);
} else if (typeof value === 'object') {
return Object.keys(value).reduce((all, key) => {
all[key] = trimRecursively(value[key]);
return all;
}, {});
} else if (typeof value === 'string') {
return value.trim();
} else {
return value;
}
}
console.log(trimRecursively(x));
console.log(x);
My solution works for any type of value
, and it also does not mutate the original object!
Try this:
function trimAll(obj) {
for (let k in obj) {
if (typeof obj[k] === 'string') obj[k] = obj[k].trim();
else if (typeof obj[k] === 'object' && !(obj[k] instanceof Array)) trimAll(obj[k]);
}
}