How do I convert all property values in an object to type string?
You can use a recursive
method which looks through all the keys
.
The Object.keys()
method returns an array of a given object's own enumerable properties.
There are two cases:
if
typeof
operator returnsobject
, then you have to recall the function.otherwise, you just need to apply
String()
method.
But you can use ternary
operator for one-line
solution.
typeof myObj[key] == 'object' ? replace(myObj[key]) : myObj[key]= myObj[key].toString();
var myObj = {
myProp1: 'bed',
myProp2: 10,
myProp3: {
myNestedProp1: 'desk',
myNestedProp2: 20
}
};
function replace(myObj){
Object.keys(myObj).forEach(function(key){
typeof myObj[key] == 'object' ? replace(myObj[key]) : myObj[key]= String(myObj[key]);
});
}
replace(myObj);
console.log(myObj);
Object.keys should be fine, you just need to use recursion when you find nested objects. To cast something to string, you can simply use this trick
var str = '' + val;
var myObj = {
myProp1: 'bed',
myProp2: 10,
myProp3: {
myNestedProp1: 'desk',
myNestedProp2: 20
}
};
function toString(o) {
Object.keys(o).forEach(k => {
if (typeof o[k] === 'object') {
return toString(o[k]);
}
o[k] = '' + o[k];
});
return o;
}
console.log(toString(myObj));