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]'
}
]
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.
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)
Related
I have a comma-separated string being pulled into my application from a web service, which lists a user's roles. What I need to do with this string is turn it into an array, so I can then process it for my end result. I've successfully converted the string to an array with jQuery, which is goal #1. Goal #2, which I don't know how to do, is take the newly created array, and remove all characters before any array item that contains '/', including '/'.
I created a simple work-in-progress JSFiddle: https://jsfiddle.net/2Lfo4966/
The string I receive is the following:
ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC
ABCD/ in the string above can change, and may be XYZ, MNO, etc.
To convert to an array, I've done the following:
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
Using console.log, I get the following result:
["ABCD", "ABCD/Admin", "ABCD/DataManagement", "ABCD/XYZTeam", "ABCD/DriverUsers", "ABCD/RISC"]
I'm now at the point where I need the code to look at each index of array, and if / exists, remove all characters before / including /.
I've searched for a solution, but the JS solutions I've found are for removing characters after a particular character, and are not quite what I need to get this done.
You can use a single for loop to go through the array, then split() the values by / and retrieve the last value of that resulting array using pop(). Try this:
for (var i = 0; i < currentUserRole.length; i++) {
var data = currentUserRole[i].split('/');
currentUserRole[i] = data.pop();
}
Example fiddle
The benefit of using pop() over an explicit index, eg [1], is that this code won't break if there are no or multiple slashes within the string.
You could go one step further and make this more succinct by using map():
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',').map(function(user) {
return user.split('/').pop();
});
console.log(currentUserRole);
You can loop through the array and perform this string replace:
currentUserRole.forEach(function (role) {
role = role.replace(/(.*\/)/g, '');
});
$(document).ready(function(){
var A=['ABCD','ABCD/Admin','ABCD/DataManagement','ABCD/XYZTeam','ABCD/DriverUsers','ABCD/RISC'];
$.each(A,function(i,v){
if(v.indexOf('/')){
var e=v.split('/');
A[i]=e[e.length-1];
}
})
console.log(A);
});
You could replace the unwanted parts.
var array = ["ABCD", "ABCD/Admin", "ABCD/DataManagement", "ABCD/XYZTeam", "ABCD/DriverUsers", "ABCD/RISC"];
array = array.map(function (a) {
return a.replace(/^.*\//, '');
});
console.log(array);
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
for(i=0;i<currentUserRole.length;i++ ){
result = currentUserRole[i].split('/');
if(result[1]){
console.log(result[1]+'-'+i);
}
else{
console.log(result[0]+'-'+i);
}
}
In console, you will get required result and array index
I would do like this;
var iur = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC',
arr = iur.split(",").map(s => s.split("/").pop());
console.log(arr);
You can use the split method as you all ready know string split method and then use the pop method that will remove the last index of the array and return the value remove pop method
var importUserRole = ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
for(var x = 0; x < currentUserRole.length; x++;){
var data = currentUserRole[x].split('/');
currentUserRole[x] = data.pop();
}
Here is a long way
You can iterate the array as you have done then check if includes the caracter '/' you will take the indexOf and substact the string after the '/'
substring method in javaScript
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
for(var x = 0; x < currentUserRole.length; x++){
if(currentUserRole[x].includes('/')){
var lastIndex = currentUserRole[x].indexOf('/');
currentUserRole[x] = currentUserRole[x].substr(lastIndex+1);
}
}
I have a ajax request which returns data in json format like
{
"response_code": 1,
"response_data": {
"ext": [
{
"client_id":"1003",
"company_name":"Reachmediagg"
},
{
"client_id":"1004",
"company_name":"RaSpecial"
}
],
"row_count":2
},
"response_error":""
}
As you can see the data is inside the ext array inside json object, now I have to get the row number of the data, so I want for example row number of client_id 1004, which is 2. How will I do that in javascript?
You have to loop through the ext array in your JSON and find the element that holds the correct client_id. The function described below does just that.
function get_row_number(data, client_id) {
var ext = data.ext;
// Loop through all the clients and try to find the one with the given client_id
for (var i = 0; i < ext.length; i++) {
if (ext[i].client_id == client_id)
return i;
}
// Return -1 if the client_id could not be found
return -1;
}
Technically the data doesn't have row numbers. Only in how you read the data can you infer/assign a row number.
Note that ext is an array. You can loop over that array until you find the record you want and keep a counter. For example:
var counter = 0;
for (;counter <= response_data.ext.length; counter++) {
if (response_data.ext[counter].client_id == 1004) {
break;
}
}
// here "counter" is the "row number" where client_id == 1004
You can also extract this into a function where the target client_id is a parameter (or the condition itself is a parameter, allowing you to look for more than just client_id).
I have 1 String Variable in JavaScript which contains 3 Comma separated values shown below:
var session = "mick#yahoo.com,123456,f_id=8";
I want to get all above 3 comma separated values in 3 different variables. What I have achieved so far is getting last comma separated value in elem2 variable and getting other 2 comma separated values 1st and 2nd one in elem1 variable.
var elem1 = session.split(",");
var elem2 = elem1.pop();
document.write("elem1 = "+elem1+"<br/>elem2 = "+elem2);
So my program is not working fine as I wants, please I need quick working solution so that I have another variable elem3 and I will get following output in my browser:
elem1 = mick#yahoo.com
elem2 = 123456
elem3 = f_id=8
You could try the following:
// Initially, we split are comma separated string value on commas.
// In the values an array of these values is stored.
var values = session.split(",");
// Then we get each value based on it's position in the array.
var email = values[0];
var number = values[1];
var id = values[2];
As a side note, I would suggest you use meaningful names for your variables like above. The names elem1, elem2 and elem3 are a bit vague and in future thses namings may obscure even you, let alone another reader of your code.
You can also store the session data in a JavaScript Object. Below iterates through each split string and adds it to an Object.
var myData = {};
// ...
for(var i = 0, x = session.split(","); i < x.length; i++) {
switch(i) {
case 0: myData.email = x[i]; break;
case 1: myData.number = x[i]; break;
case 2: myData.f_id = x[i]; break;
}
}
If you're dealing with multiple data values, it's best to make an array of objects, like so.
var myData = [];
// ...
myData.push({
email: x[0],
number: x[1],
f_id: x[2]
});
And so on. This is a form of JSON Notation. The output would look like this:
[
{
email: "mick#yahoo.com",
number: "123456",
f_id: "f_id=8"
},
{
// Another session, etc.
}
]
You could also use string.replace with a callback as parameter. Very flexible!
Check this for more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
For your usecase you may end up with:
function writeParts(match, email, number, id, offset, string) {
document.write("email = "+email+"<br/>number = "+number);
}
// match not-comma followed by a comma (three times)
session.replace(/([^,]+),([^,]+),([^,]+)/, writeParts);
I have file in csv format:
info,value
"off to home","now"
"off to office","tomorrow"
I want json out of this using jquery but couldnt find any help.Isnt it possible to use jquery for this?
My intended output is :
{
"items": [
{
"info": "off to home",
"value": "now"
},
{
"info": "off to office",
"value": "tomorrow"
},
]
}
PFB the code which i implemented. but it is not working
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="csvjson.js"></script>
<script>
$.ajax("data.csv", {
success: function(data) {
var jsonobject = csvjson.csv2json(data);
alert(jsonobject);
},
error: function() {
alert("error")
}
});
</script>
</head>
<body>
</body>
</html>
Using jquery-csv, specifically the toObjects() method
$.ajax({
url: "data.csv",
async: false,
success: function (csvd) {
var items = $.csv.toObjects(csvd);
var jsonobject = JSON.stringify(items);
alert(jsonobject);
},
dataType: "text",
complete: function () {
// call a function on complete
}
});
Note: You'll need to import the jquery-csv library for this to work.
What this does is transform the CSV data into an array of objects.
Since the first line contains headers, jquery-csv knows to use those as the keys.
From there the data is transformed to JSON using stringify().
If you need a wrapper object, just create one and attach the data to it.
var wrapper = {};
wrapper.items = items;
alert(wrapper);
Disclaimer: I'm the author of jquery-csv
Useful link, I have found. Maybe help someone.
http://jsfiddle.net/sturtevant/AZFvQ/
function CSVToArray(strData, strDelimiter) {
// Check to see if the delimiter is defined. If not,
// then default to comma.
strDelimiter = (strDelimiter || ",");
// Create a regular expression to parse the CSV values.
var objPattern = new RegExp((
// Delimiters.
"(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
// Quoted fields.
"(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
// Standard fields.
"([^\"\\" + strDelimiter + "\\r\\n]*))"), "gi");
// Create an array to hold our data. Give the array
// a default empty first row.
var arrData = [[]];
// Create an array to hold our individual pattern
// matching groups.
var arrMatches = null;
// Keep looping over the regular expression matches
// until we can no longer find a match.
while (arrMatches = objPattern.exec(strData)) {
// Get the delimiter that was found.
var strMatchedDelimiter = arrMatches[1];
// Check to see if the given delimiter has a length
// (is not the start of string) and if it matches
// field delimiter. If id does not, then we know
// that this delimiter is a row delimiter.
if (strMatchedDelimiter.length && (strMatchedDelimiter != strDelimiter)) {
// Since we have reached a new row of data,
// add an empty row to our data array.
arrData.push([]);
}
// Now that we have our delimiter out of the way,
// let's check to see which kind of value we
// captured (quoted or unquoted).
if (arrMatches[2]) {
// We found a quoted value. When we capture
// this value, unescape any double quotes.
var strMatchedValue = arrMatches[2].replace(
new RegExp("\"\"", "g"), "\"");
} else {
// We found a non-quoted value.
var strMatchedValue = arrMatches[3];
}
// Now that we have our value string, let's add
// it to the data array.
arrData[arrData.length - 1].push(strMatchedValue);
}
// Return the parsed data.
return (arrData);
}
function CSV2JSON(csv) {
var array = CSVToArray(csv);
var objArray = [];
for (var i = 1; i < array.length; i++) {
objArray[i - 1] = {};
for (var k = 0; k < array[0].length && k < array[i].length; k++) {
var key = array[0][k];
objArray[i - 1][key] = array[i][k]
}
}
var json = JSON.stringify(objArray);
var str = json.replace(/},/g, "},\r\n");
return str;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
You can use Alasql library. Alasql can load the data file from server, parse it and put the result to array of JSON objects.
This is the code:
<script src="alasql.min.js"></script>
<script>
alasql('SELECT * FROM CSV("items.csv",{headers:true})',[],function(res){
var data = {items:res};
});
</script>
If you want to modify data (for example, use only one column or filter), you can do it "on the fly".
Alasql understands the headers and use them for SELECT statement:
alasql('SELECT info FROM CSV("items.csv") WHERE value = "now"',[],function(res){
console.log(res);
});
I think jquery csv plugin will be helpful to convert your CSV to an array, then you can use jquery json.
BTW, you can use $.get() to read your CSV file from server.
I am having a Array which is generated by my Javascript in run time.
once that array is full with all the values I want to send it using POST to the server.
How can I do that ...
Pseudo code:
for(i=0;i<result.data.length;i++)
{
result.data[i].id
}
$.post("receiver.php", { xxxxx }, function(data){ console.log(data);});
How can I get that xxxx updated in the post
I checked the documentation in jquery but they are expecting to give all the values in POST.I do not want to do that.
Also, I want to send post only once so that traffic will be less.
EDIT
You can use join() to get all your array values converted to a string, using some char to separate it.
EDIT 2: As Kumar said he was using 2 arrays
var idsArray;
var namesArray;
for(i=0;i<result.data.length;i++)
{
idsArray[] = result.data[i].id;
namesArray[] = result.data[i].name;
}
var ids = idsArray.join(",");
var names = namesArray.join(",");
$.post("receiver.php", { ids:ids, names:names }, function(data){ console.log(data);});
similar to iBlue's comment, You can just send an object with post; you don't have to define the object in the post function, { } are simply the delimiters to define objects, which are similar to PHP associative arrays:
$.post('reciever.php', myData, function(data){ /*callback*/ });
The only thing is that you setup myData as an object like follows:
myData = {
0: 'info',
1: 'info'
}
//or even something like this
myData = {
someProp: 'info',
someProp2: {
anotherProp: 'moreInfo'
}
}
you can also use non-numerical indexes with objects, and easily add properties:
myData[2] = 'info';
or you can loop through it, just in a slightly different way:
for(i in myData){
myData[i]; //Do something with myArr[i]
}
the for in loop will also loop through non-numerical properties. And you can still get the length of myData by
myData.length;
EDIT:
Instead of sending a string:
IDs = {}
Names = {}
for(var i = 0; i < result.data.length; i++){
IDs[i] = result.data[i].id;
Names[i] = result.data[i].name;
}
$.post('reciever.php', {IDs: IDs, Names: Names}, function(data){});
In the PHP file you would access them like so
$_POST['IDs'][0] = "some id";
$_POST['Names'][0] = "some name";
EDIT:
Actaully I think the indexes are sent as strings, so might have to do
$_POST['IDs']['0']
Not sure, but it seems like you want to do this:
var sendObj = {};
for (var i=0; i<result.data.length; i++) {
var id = result.data[i].id,
name = result.data[i].name; // or some similiar computation
sendObj[name] = id;
}
$.post("receiver.php", sendObj, function(data){ console.log(data);});
This will send the result.data as name=id-value-pairs.