
[英]How to modify a string in an array to contain special characters using javascript
[英]how to modify string with special characters to array of objects in javascript
我有一个带有特殊字符的字符串,我必须使用 javascript 修改为 object 数组
所以在一个字符串中,总是在下划线之前被认为是name
并且在下划线被认为是type
之后
试过了
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}
]
先使用split
;
并使用 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.