Home > Back-end >  String-split into array of objects
String-split into array of objects

Time:05-13

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?

CodePudding user response:

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.

Mdn docs on Array.map

In your case, you want something like: myString.split(",").map(el => ({ id: el });

CodePudding user response:

Here's your answer in typescript:

interface Output {
    id: string
}

const initialString: string = 'Example1,Example2,Example3,Example4,Example5';

const finalArray: Output[] = [].concat(initialString.split(',').map(item => {
    return { id: item }
}))

CodePudding user response:

If your string items have always the same length, (always follow a standar format like "id1,id2,id3" or "part1.part2,part3") you could use .substring(index from, index to 1)

Like this:

var array : string[] = []; 

//string.length 4 will allow to susbtring the last item of the string
for(var n = 0; n < (string.length 4); i  ){

  //taking "id1" as an example, substring from 0 - 4 whill return "id1" 
  array.push(string.substring(n, n 4));
 // adding  4 to n will make it substring from after the comma on the next 
 //iteration and return "id2"
  n  = 4;

}

This way you should try to create a standar to your string items

Here's some doc to substring :

https://www.tutorialspoint.com/typescript/typescript_string_substring.htm

  • Related