0

I have a string with special characters, I have to modify to array of object using javascript

so in a string, always before underscore considered as name

and after underscore is considered as type

  • if semicolon is present, then can be two diff objects

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}
]

1 Answer 1

2

Use split first on ; and use flatMap and use split on _

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));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.