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

Related searches

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.

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

Objects, these properties are all right let obj = { for: 1, let: 2, return: 3 }; alert( obj.for + obj. let + obj.return ); // 6 Other types are automatically converted to strings. We can't set it to a non-object value:. We can convert Object to String in java using toString() method of Object class or String.valueOf(object) method. You can convert any object to String in java whether it is user-defined class, StringBuilder, StringBuffer or anything else. Here, we are going to see two examples of converting Object into String. In the first example, we are going to convert Emp class object into String which is an user-defined class. In second example, we are going to convert StringBuilder to String.

Object to primitive conversion, In the chapter Type Conversions we've seen the rules for numeric, We can fine- tune string and numeric conversion, using special object methods output alert( obj); // using object as a property key anotherObj[obj] = 123 There is no “ boolean” hint (all objects are true in boolean context) or anything else� In TypeScript, object is the type of all non-primitive values (primitive values are undefined, null, booleans, numbers, bigints, strings). With this type, we can’t access any properties of a value. Object vs. object: primitive values # Interestingly, type Object includes primitive values: function func1 (x: Object) { } func1('abc'); // OK. Why?

You can use lodash cloneDeepWith function.

import * as _ from 'lodash';

var myObj = {
  myProp1: 'bed',
  myProp2: 10,
  myProp3: {
    myNestedProp1: 'desk',
    myNestedProp2: 20
  }
};

function toString(obj) {
    return _.cloneDeepWith(obj, val => val.toString());
}

console.log(toString(myObj));

Object.prototype.toString(), The toString() method returns a string representing the object. By default, the toString() method is inherited by every object descended from Object . object, toString() returns " [object type ] ", where type is the object type. the name , breed , color , and sex of the object, in the form " property = value; ". Object.values() returns an array whose elements are the enumerable property values found on the object. The ordering of the properties is the same as that given by looping over the property values of the object manually. Polyfill. To add compatible Object.values support in older environments that do not natively support it, you can find a

Not exactly what was asked, but it can be useful. Implementation with lodash

const person = {
  name: 'John',
  age: 25,
  address: {
    street: 'Green',
    houseNumber: 11
  },
  verified: true,
  bio: null,
  createdAt: NaN
};

function convertValuesToStringsDeep(obj) {
  return _.cloneDeepWith(obj, value => {
    return !_.isPlainObject(value) ? _.toString(value) : undefined;
  });
}

const copy = convertValuesToStringsDeep(person);
console.log(copy);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>

Object.values(), The Object.values() method returns an array of a given object's own (The only difference is that a forin loop enumerates properties in the prototype chain as well.) expected output: Array ["somestring", 42, false]. 9. . Console.Write("The entire string: ") For x As Integer = 0 To test.Length - 1 Console.Write(pinfo.GetValue(test, { x })) Next Console.WriteLine() End Sub Sub ShowIndividualCharacters(pinfo As PropertyInfo, value As Object, ParamArray indexes() As Integer) For Each index In indexes Console.WriteLine("Character in position {0,2}: '{1}'", index, pinfo.GetValue(value, { index })) Next Console.WriteLine() End Sub End Module ' The example displays the following output: ' Character in position 0: 'a

Use the toString() method; mozilla reference here

var myObj = {
  myProp1: 'bed',
  myProp2: (10).toString(),
  myProp3: {
    myNestedProp1: 'desk',
    myNestedProp2: (20).toString()
  }
};

PropertyInfo.GetValue Method (System.Reflection), Returns the property value of a specified object. Reflection; public class Planet { private String planetName; private Double 0: 'a' // Character in position 6: 'g' // Character in position 25: 'z' // // The entire string: abcdefghijklmnopqrstuvwxyz home; articles. Chapters and Sections > if object is not null and hold string value these are 4 type to convert object to string

The first command gets all processes by using the Get-Process cmdlet. The command passes them to the Select-Object cmdlet, which selects the process name and process ID. At the end of the pipeline, the command converts the output to comma separated values, without type information, by using the ConvertTo-Csv cmdlet.

So the battle really comes down to toString() and String() when you want to convert a value to a string. This one does a pretty good job. This one does a pretty good job. Except it will throw an

You can do this before your object is created or after and it will still work. This is what makes this different then using Add-Member with a script property. When you use Add-Member the way I referenced earlier, it only exists on that specific instance of the object. This one applies to all objects with this TypeName. Function parameters

Comments
  • Please post what you have tried.
  • @asw1984, it's working for you ?
  • It seems that someone it playing with downvote button. +1 anyway :)
  • Exactly what I was looking for. What about a scenario where the data isn't an object, but an array of objects, each needing the same treatment as the object above? Wrapping the forEach in another forEach seems inefficient form a performance standpoint. Perhaps there's a better way to account for the array of objects?
  • Side note: Calling toString() works fine in this case if there are only strings and numbers, but it would fail if the values could also be null or undefined. For these cases, String(value) or '' + value would work.
  • @FelixKling, yes, that's true. Updated.
  • This doesn't seem to work - care to link to a working jsfiddle?
  • (1) This isn't valid syntax (it needs to have two periods) and (2) I think the OP is asking how to do this using an already-created myObj -- otherwise, why not just put the numbers in quotes instead of doing .toString()?
  • I see, then should we use myObj.toString() ?
  • It seems like the OP wants to iterate over all properties and sub-properties (and so on recursively) of the object and convert them to strings.