Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
42
rated 0 times [  44] [ 2]  / answers: 1 / hits: 25915  / 7 Years ago, fri, october 27, 2017, 12:00:00

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.


More From » object

 Answers
61

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));




[#56082] Thursday, October 26, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dequant

Total Points: 88
Total Questions: 99
Total Answers: 95

Location: Ukraine
Member since Sun, Dec 13, 2020
4 Years ago
;