[英]How to convert string in an array?
From http response I received an object like this:从 http 响应中,我收到了一个这样的对象:
{"[3, company1]":["role_user"], "[4, company2]":["role_admin"] }
The key is an array...Is there a way in typescript to convert the key键是一个数组...打字稿中有没有办法转换键
"[3, company1]"
in an array like this在这样的数组中
[3, "company1"]
? ?
You can combine Object.keys with map and transform the string to array with split您可以将 Object.keys 与 map 结合使用,并使用 split 将字符串转换为数组
let data = {"[3, company1]":["role_user"], "[4, company2]":["role_admin"] } let keys = Object.keys(data) .map( el => el.replace('[', '') .replace(']', '') .split(',') .map(el => el.trim()) .map(el => isNaN(parseFloat(el)) ? el : parseFloat(el)) ) console.log("Keys: ", keys)
Here is the fiddle: https://jsfiddle.net/to38g6cb/1/这是小提琴: https : //jsfiddle.net/to38g6cb/1/
What do you want to convert the keys to?您想将密钥转换为什么?
if want to convert it to a normal array then the below should do.如果要将其转换为普通数组,则应执行以下操作。
const httpResponse = { "[3, company1]": ["role_user"], "[4, company2]": ["role_admin"] }; const convertedKeys = Object.keys(httpResponse).map(value => { let keyArray = value.replace("[", "").replace("]", "").split(", "); return [parseInt(keyArray[0]), keyArray[1]]; }); console.log(convertedKeys);
If the above is not what you wanted, please kindly rephrase your question again.如果以上不是您想要的,请再次重新表述您的问题。
You can remove the first and last character using slice(1,-1)
and split
the string at /\\s*,\\s*/
(comma with optional spaces on either side).您可以使用slice(1,-1)
删除第一个和最后一个字符slice(1,-1)
并在/\\s*,\\s*/
处split
字符串(逗号两侧带有可选空格)。
Then convert the first part to a number and return the array然后将第一部分转换为数字并返回数组
const input = { "[3, company1]": ["role_user"], "[4, company2]": ["role_admin"] } const output = Object.keys(input).map(k => { const [n, comp] = k.slice(1,-1).split(/\\s*,\\s*/) return [+n, comp] }) console.log(JSON.stringify(output))
It would have been easier if the company1
part were already quoted, so that you could just use JSON.parse
.如果已经引用了company1
部分会更容易,这样您就可以使用JSON.parse
。 In fact, let's just do that!事实上,让我们这样做吧! Put quotes around the company1
part with search and replace.通过搜索和替换在company1
部分周围加上引号。
let key = `[3, company1]`; let obj = JSON.parse(key.replace(/[$A-Z_]\\w*/gi, '"$&"')) console.log(obj);
Note: I'm guessing at what characters might be valid and went with something that looks vaguely like a JavaScript identifier.注意:我在猜测哪些字符可能是有效的,并且带有一些看起来有点像 JavaScript 标识符的东西。 [$A-Z_]\\w*
Obviously not commas and right square brackets, due to deserialization ambiguity. [$A-Z_]\\w*
显然不是逗号和右方括号,因为反序列化的歧义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.