简体   繁体   English

如何将带有特殊字符的字符串修改为 javascript 中的对象数组

[英]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之后

  • if semicolon is present, then can be two diff objects如果分号存在,则可以是两个 diff 对象

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM