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?
Here is a solution making these assumptions:
|
specialty
(string value), the second one the userid
(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:
const str = "Tuba|203488|Music Theory|301071";
let result = str.split('|').reduce((acc, val, idx, arr) => {
if(idx % 2) {
acc.push({
specialty: arr[idx - 1],
userid: Number(val)
});
}
return acc;
}, []);
console.log(result);
Output:
[
{
"specialty": "Tuba",
"userid": 203488
},
{
"specialty": "Music Theory",
"userid": 301071
}
]