Convert string to object in typescript?

20,955

Solution 1

You can use JSON.parse to convert from string to objects:

     var x = require('is-valid-glob');
     var y = '[]';//'foo/*.js' any user provided string
     // this will check if the user has provided an array object if so it 
     //will do a json.parse to remove the '' and then verify the string for a glob.
     x(y[1] !== '['?y:JSON.parse(y));

Solution 2

Try with eval it is used to convert string into equivalent object for an example,

var a="[]";
console.log(a);// this will print "[]" as a string.
console.log(eval(a));// this will print an array object. With 0 length array object.
Share:
20,955
Akshay
Author by

Akshay

I am a Computer Science and Technology Enthusiast. I am open to new challenging opportunities and l like to learn things by doing them.

Updated on November 27, 2020

Comments

  • Akshay
    Akshay over 3 years

    I am trying to validate a glob expression using Is-Valid-Glob which accepts string and array. The value which needs to be validated is received from a text field. The problem is that if we pass an invalid glob expression it produces the wrong result as every input is received as a string. For example:- If user inputs [] (invalid glob) its gets assigned to model variable as string '[]' and validation is done on '[]' instead of [] value. Is there a way by which we convert the value from string variable to object variable (only the value should not get type) and do validation?

    PS: I am using Angular 2.

  • Akshay
    Akshay over 6 years
    thanks, @deepak, eval will not be helpful in case of strings. eg "foo/*.js" (valid glob).
  • Akshay
    Akshay over 6 years
    Hi @Vikramjit, I am using the similar hack serves the purpose. Looking for a more satisfiable solution. Also, need to add cases for {} (invalid glob), it will pass in this scenario
  • Noam Gal
    Noam Gal about 3 years
    Doesn't work. In case of a string, it splits the string to an array where each element is a single character from that string.