Angular split string to array

Viewed 2385

I have a String message like that :

messages = "Line 249 : Validation error, Line 287 : Validation error"

I want to split this message like this :

messages [] = [ { position: 1, message: 'Line 249 : Validation error' },

{ position: 2, message: 'Line 287 : Validation error' }]

Could you please help with this thank you.

2 Answers

I think your error message can be split into an array using javascript split method. so

messages = message.split(',') 

will do the magic But to add your position,

let messages = "Line 249 : Validation error, Line 287 : Validation error"

messages= messages.split(',').map((x,index)=>{
    let obj ={}
     obj.position=index+1;
     obj.message = x
     return obj;
 });
 
 console.log( messages )

The easiest way to turn a string into an array of objects is to first split the string using the delimiter, which in this case is the comma, so start with.

const test = "Line 249 : Validation error, Line 287 : Validation error";
const parts = test.split(",");

Then, you want to use the map array function to return an object for each part that's been split. The es6 map function has a callback that returns the piece of the array and the index in which it was found. you don't want the index, but rather an ordinal (per your example above)

Here's what i would do:

const test = "Line 249 : Validation error, Line 287 : Validation error"; 
const parts = test.split(",").map((text, index) => {
  return {
    position: index+1,
    message: text.trim()
  }
});

Now, the parts variable holds an array of objects that matches your required output

Related