0

I am beginner in Angular and TS.
I want to get array of integer like [1,2,3,4] , but jasper server gives an output as string "[1,2,3,4]".
So how I change it using Type Script.

Data :

[
    {  
       LABEL:'CR FAILURE MESSAGES',
       DATASET:'[3,3,10,15,21,35,35,81]'
    },
    {  
       LABEL:'CR SUCCESS MESSAGES',
       DATASET:'[1,4,31,34,63,78,219,312,1076]'
    },
    {  
       LABEL:'CR TOTAL MESSAGES',
       DATASET:'[4,7,55,66,93,98,300,312,1086]'
    },
    {  
       LABEL:'PR FAILURE MESSAGES',
       DATASET:'[2,5,6,12,18,19,23,48]'
    },
    {  
       LABEL:'PR SUCCESS MESSAGES',
       DATASET:'[4,5,10,22,32,65,101,139]'
    }
]
0

2 Answers 2

1

You can use JSON.parse to do this for you.

let obj = {
    "LABEL":"CR FAILURE MESSAGES",
    "DATASET":"[3,3,10,13,21,35,35,81]"
};

let datasetArray = JSON.parse(obj.DATASET); // Generates the array
console.log(datasetArray);

Is there a reason why you get an array wrapped in a string? If the server just returned a stringified JSON object, I would expect that calling JSON.parse on the whole thing would just build the array inline with the rest of the object.

Sign up to request clarification or add additional context in comments.

2 Comments

can you check agin
You should be able to extend the same approach over an array. Just call JSON.parse on every DATASET field.
1

Here's my solution

You can remove the first and the last characters to get "1,2,3,4" and then use split in order to turn it into array

The code is well commented take your time to understand it line by line;

var input = "[3,3,10,13,21,35,35,81]"
console.log(input)

//cleaning the input
var cinput = input.substr(1).slice(0, -1);
console.log(cinput)
//using split to turn it into an array by using the ',' as seperator
var output = cinput.split(',')
//the result
console.log(output)
var parsedarray = []

//to parse each array element to int
for (var i = 0, len = output.length; i < len; i++) {
  parsedarray[i] = parseInt(output[i]);
}
//parsed numbers inside the array
console.log(parsedarray)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.