I have a string that looks like the following:
_/_-- Select a Sub-server (optional) --_|_509_,Subserver 509_|_510_,Subserver 510_|_511_Subserver 511
And I am trying to get the following output from it:
const arr = [
{ id: "", text: "-- Select a Sub-server (optional) --"},
{ id: "509", text: "Subserver 509"},
{ id: "510", text: "Subserver 510"},
{ id: "511", text: "Subserver 511"},
]
This is the code I have built but I am missing something because the output is not as expected:
const values = "_/_-- Select a Sub-server (optional) --_|_509_,Subserver 509_|_510_,Subserver 510_|_511_Subserver 511";
const parts = values.split("_|_").filter(part => part.trim() !== "");
const arr = parts.map(part => {
const [id, text] = part.split("_,");
return { id: id || "", text: text || "" };
});
this is the result I got from my code:
console.log(arr);
[
{ id: '_/_-- Select a Sub-server (optional) --', text: '' },
{ id: '509', text: 'Subserver 509' },
{ id: '510', text: 'Subserver 510' },
{ id: '511_Subserver 511', text: '' }
]
Why are the first and last ids wrong and are missing the text value? Can I get some help identifying where is my issue?
Note: I am open to suggestions and improvements not tied to my code.
>Solution :
You don’t have _, separators in the first and last items, so you can’t use that as the delimiter between the ID and the value.
Also, you have _/_ before the first element, that won’t be removed by any of your code. You could use another regexp to treat that as a delimiter in the first split.
Since the comma is optional, you could use a regular expression as the delimiter: /_,?/ matches _ optionally followed by ,.
const values = "_/_-- Select a Sub-server (optional) --_|_509_,Subserver 509_|_510_,Subserver 510_|_511_Subserver 511";
const parts = values.split(/_\|_|_\//).filter(part => part.trim() !== "");
const arr = parts.map(part => {
const [id, text] = part.split(/_,?/);
return { id: id || "", text: text || "" };
});
console.log(arr);