I am trying to split a string into an array of objects in TS.
I have the following (example) string:
Example1,Example2,Example3,Example4,Example5
And I’m trying to parse it into:
[
{
"id":"Example1"
},
{
"id":"Example2"
},
{
"id":"Example3"
},
{
"id":"Example4"
},
{
"id":"Example5"
}
]
using split() i can easily split it into an array of strings, but that doesn’t quite cover my use case in this instance.
Can anyone help me out?
>Solution :
Take a look at the JavaScript Array method map. You can perform any transformation over array items with it, such as turning them into plain objects.
In your case, you want something like:
myString.split(",").map(el => ({ id: el });