Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert all property values in an object to type string?

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.

like image 525
asw1984 Avatar asked Oct 27 '17 20:10

asw1984


People also ask

How do you transform an object into a string?

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.

Which method is useful to get all values of object in a string form?

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.

How do you convert an object to a string in Python?

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.

Can an object property be a string?

Objects are associative arrays with several special features. They store properties (key-value pairs), where: Property keys must be strings or symbols (usually strings).


1 Answers

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));
like image 53
Martin Adámek Avatar answered Sep 20 '22 22:09

Martin Adámek