如何将字符串的用户输入转换为对象 假设我有一个字符串数组
["code:213123", "code:213123", "code:213123"]
如何将其转换为obj数组 所以结果应该是这样的:
[{code: "213123"},...]
答案 0 :(得分:1)
new Function
或eval
可以这样转换:
let params = '["code:213123", "code:213123", "code:213123"]';
params = new Function(`return JSON.parse(JSON.stringify(${params}));`)();
答案 1 :(得分:0)
根据您的问题,假设用户严格按照code: x code: y code: z
格式输入文字作为字符串,您可以执行以下操作:
`code: 2a31sdd23
code: asdw12ds3
code: 213sad123`
.replace(/[\r\n]*/g,'')
.replace(/code:\s+/g,'')
.replace(/[\s\t]+/g,' ')
.split(' ')
.reduce((p,c) => {p.push({code: c}); return p}, [])
// Output
// [{code: "2a31sdd23"}, {code: "asdw12ds3"}, {code: "213sad123"}]