I have the following string:
const str = "Tuba|203488|Music Theory|301071"
I would like to convert it to an array of objects like so:
[
{specialty: "Tuba",
userid:203488},
{specialty: "Music Theory",
userid:301071}
]
How can I do this in javascript?
4
Answers
You can split the string by the pipe and then iterate over the resultant array, incrementing by 2, adding and object to a final result array:
You can do like this:
Here is a solution making these assumptions:
|
specialty
(string value), the second one theuserid
(number value)[{ specialty: String, userid: Number }]
The solution first splits the input string on
|
, then uses a.reduce()
to build the resulting array of objects:Output:
Here’s how you can do it.