I'm working with an object containing properties with values that are either type string or type number. Some properties are nested objects, and these nested objects also contain properties with values that could be either type string or type number. Take the following object as a simplified example:
var myObj = {
myProp1: 'bed',
myProp2: 10,
myProp3: {
myNestedProp1: 'desk',
myNestedProp2: 20
}
};
I want all of these values to be type string, so any values that are type number will need to be converted.
What is the most efficient approach to achieving this?
I've tried using for..in and also played around with Object.keys, but was unsuccessful. Any insights would be greatly appreciated.
Stringify a JavaScript ObjectUse the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.
values() Method: The Object. values() method is used to return an array of the object's own enumerable property values. The array can be looped using a for-loop to get all the values of the object.
Converting Object to String Everything is an object in Python. So all the built-in objects can be converted to strings using the str() and repr() methods.
Objects are associative arrays with several special features. They store properties (key-value pairs), where: Property keys must be strings or symbols (usually strings).
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));
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