[英]how to modify string with special characters to array of objects in javascript
I have a string with special characters, I have to modify to array of object using javascript我有一个带有特殊字符的字符串,我必须使用 javascript 修改为 object 数组
so in a string, always before underscore considered as name
所以在一个字符串中,总是在下划线之前被认为是
name
and after underscore is considered as type
并且在下划线被认为是
type
之后
tried试过了
var arr = str2.split(';');
var result = arr.find( e => {
e.split(/[_,]/);
}).map(i => ({
name: i[0],
type: i.shift()
}));
var str1 = "xyz_dell,asus";
var str2 = "abc_new;red_old;zen_sg,my"
Expected Output for str1
[
{name: xyz, type: dell,asus}
]
Expected Output for str2
[
{name: abc, type: new},
{name: red, type: old},
{name: zen, type: sg, my}
]
Use split
first on ;
先使用
split
;
and use flatMap and use split
on _
并使用 flatMap 并在
_
上使用split
const process = (str) => str.split(";").flatMap((item) => { const [name, type] = item.split("_"); return { name, type }; }); var str1 = "xyz_dell,asus"; var str2 = "abc_new;red_old;zen_sg,my"; console.log(process(str1)); console.log(process(str2));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.