typescript 在打字稿中将字符串转换为对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47974559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert string to object in typescript?
提问by Akshay
I am trying to validate a glob expression using Is-Valid-Globwhich 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?
我正在尝试使用接受字符串和数组的Is-Valid-Glob来验证 glob 表达式。从文本字段接收需要验证的值。问题是,如果我们传递一个无效的 glob 表达式,它会产生错误的结果,因为每个输入都是作为字符串接收的。例如:- 如果用户输入 [](无效的 glob),它会作为字符串 '[]' 分配给模型变量,并且验证是在 '[]' 而不是 [] 值上完成的。有没有办法将值从字符串变量转换为对象变量(只有值不应获取类型)并进行验证?
PS: I am using Angular 2.
PS:我正在使用 Angular 2。
回答by Vikramjit Roy
You can use JSON.parse to convert from string to objects:
您可以使用 JSON.parse 将字符串转换为对象:
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));
回答by Deepak Jha
Try with eval it is used to convert string into equivalent object for an example,
尝试使用 eval 它用于将字符串转换为等效对象,例如,
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.
回答by Sanjeeta
We can use Object.assign({},object) to convert string into object.
我们可以使用 Object.assign({},object) 将字符串转换为对象。