Proper way to use split-command and "," - javascript

i have following problem:
i have an array with a lot of data retrieved from mssql and hand it over to a jsp, i will simplify it in a example:
("test","1","test2","2")
those are 4 fields. With split(",") i seperate the 4 fields, so that i can take each value and assign them to html-objects.
Now through a coincidence i found out, that if the Array is filled as follows:
("test","1","test,2","2")
where "test,2" is one text, the split command seperates the 4 values to 5 values. Is there any alternative or way so that the split command ignores the "," that are part of a string of a field?
Greetings,
Kevin
Update:
Sorry for the missunderstandings guys here i tried to simplify the code as far as i can:
<script>
var jsArray = [];
<%
// Getting ArrayList from a request Attribute with a lot of data rows
ArrayList arrayList = (ArrayList)request.getAttribute("DSList");
for(int i=0;i<arrayList.size();i++){
%>
// Pushing each row to javascript array
jsArray.push("<%= ((ArrayList)arrayList.get(i))%>");
<%
}%>
// thats the split command that gets one line of the whole dataset
Stringarray = jsArray[x].substr(1,jsArray[x].length-2).split(","); // where x is the current record
</script>
now i can simply call each filed with
Stringarray[n] //where n is the field number
thats how the code looks like, the problem now is that if in one of the Strings in any record line is a "," then the split command obviously would give back the wrong field count. I hope now it's more clear what i mean

You can use non-greedy regex to filter out value inside "" and then remove "" from the words using array#map.
var string = '("test","1","test,2","2")';
var array = string.match(/"(.*?)"/g).map(function(item){
return item.replace(/"/g,'');
});
console.log(array);

Essentially, you have a backend data source and a front-end consumer. It just so happens that they reside on the same page, since you're using JSP to generate the page and the data. So treat it like a synchronous API, just embedded into the page.
How would you transmit data between and API and JavaScript? JSON.
So, stringify your result array into a JSON string and embed that into the JSP page, then JSON.parse() that in JavaScript and iterate as you would any other array.
Since I don't see your JSP code, I can't propose a more specific solution that what's linked here for creating JSON in JSP: how to add a list of string into json object in jsp? and Creating a json object in jsp and using it with JQuery

Related

How can a linq query be converted to JavaScript array containing only values?

I have a JavaScript grid library (it creates a table on the page) that accepts a JavaScript array as input, for rendering in the grid. I'm not certain, however, how to convert a Linq-to-SQL query (against a SQL Server database) to a JavaScript array containing only values.
I tried this, but it included the table column names in the JSON key (and I don't want JSON anyway, I want a JavaScript string array, unless this can be converted to an array?):
JsonConvert.SerializeObject(query)
Example of the format I need to produce:
[1,2,3],[4,5,6]
Environment: .NET Core 3.1
edit: Here is a sample of what I've currently got, this returns the less than desirable JSON (due to the query results being so large, having a JSON key for very element is going to literally double the size of the query):
Devices Table
ID Name
1 iPhone7
2 iPhone8
3 iPhone9
Needed Array (Note: no column names)
[1, "iPhone7"],[2, "iPhone8"],[3, "iPhone9"]
Current C# code in the controller method (returns undesirable key for every element currently)
var query = db.Devices;
var formattedResult = JsonConvert.SerializeObject(query);
return Ok(formattedResult);
Technically, you could do this:
var query = db.Devices.AsEnumerable()
.Select(d => new object[]{d.ID, d.Name});
var formattedResult = JsonConvert.SerializeObject(query);
return Ok(formattedResult);
But then the code on the other end of your request is going to have to translate all those arrays back into objects.
It's rarely worthwhile to complicate your model like this in order to optimize the size of your network traffic. If you're pulling enough items over the wire to make this a performance issue, you're likely to encounter a variety of other performance issues. I would first consider other options, like implementing paging.
Did you try
var query = db.Devices.ToList();
var array = JArray.FromObject(query);
return Ok(formattedResult)

Get array from sortable jQuery serialize

I have a jQuery sortable with 3 list items with the following ID's
id_1
id_2
id_3
This gets sorted by the user and serialized using the following code
var order = $("#rank").sortable('serialize');
saveResponses(order);
and printed. Which looks like this...
id[]=1&id[]=3&id[]=2
So I've got a couple of questions...
Why does the underscore get converted to "[]="
Is there a strait forward way to get an array of the original ID's? I mean without just doing a string split, and replacing the characters?
serialize converts the data into a query string. The data is formatted (converted to an array) so you can use it in a URL as a query string (GET data).
You probably want toArray:
var order = $("#rank").sortable('toArray');

pyodbc result set has data type embedded

I am querying Teradata using pyodbc and flask with the intention of charting the data using d3.
The result set has two columns, one is a decimal and the other an integer. When I pass the results to my html page and log the output I am getting something along these lines:
[(Decimal(& #39;-16.200000000& #39;), 5), (Decimal(& #39;-23.100000000& #39;), 12), (Decimal(& #39;500.300000000& #39;), 5)].
The embedded data type information is making it difficult to do anything with the result set. How can I get output to look like this instead?
[[-16.200000000, 5], [-23.100000000, 12], [500.300000000, 5]]
In other words I just want an array of arrays.
Steps I am following:
create a connection
create a cursor
execute the SQL
use fetchall() to store the rows in a variable
pass the variable to my html page using render_template
in javascript set variable equal to data passed in
var data={{dataset}};
console.log(data);
I have seen many flask examples where they take the result set and iterate through it to print the lines in the html but I want to use the resulting dataset as an input to my d3 code. Why is it displaying the data type? And why would it not also display the data type of the integer column?
I am guessing the issue is related to the row construct but I have tried creating a list instead and can't get rid of the data type information. I then get all sorts of errors due to the ampersands.
I think the better approach is as provided in this answer, as it is best to dumps the data of the query into a json object so you can easily retrieve it from the client side using JS, without the need to parse it using regex or other mechanism.
STEPS:
1 - Subclass the json.JSONEncoder:
class DecimalEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, decimal.Decimal):
return float(o) #Type conversion happens here
return super(DecimalEncoder, self).default(o)
2 - Pass the params to the template as a json object:
data = json.dumps({'pi': decimal.Decimal('3.14')}, cls=DecimalEncoder)
return render_template('mytemplate.html', dataset=data)
3 - Read back the result of the query in your JS:
var data = {{dataset}};
import re
processed = []
for piece in results:
processed.append([re.sub(".*?(-?\d+\.\d+).*", "\1", repr(piece[0])), piece[1]]
Something along those lines. It's displaying that data because it's of type Decimal (the teradata kind). I'm guessing repr() will give you the same results you're seeing in the log... then just regex it to what you want.

Split to get the text between separators?

I am making a cross domain AJAX request, and because of this, I can't pass the original array from the PHP page to my HTML page. Instead, the request gets the results as a string. I have it set up so that the syntax looks like this:
([SCHOOL] Name [/SCHOOL][STATUS] Status [/STATUS])
([SCHOOL] Other name [/SCHOOL][STATUS] Other status [/STATUS])
On my HTML page, I want to be able to form an array from these different values, in the form of:
Array (
[0] =>
[0] Name
[1] Other
[1] =>
[0] Name
[1] Other status
)
This way, I can use a for loop to get specific values.
The only problem with is that split only does just that, splits things. Is there a way in JS to find the text within separators, and form an array from it? In the example again, it'd find all text within the parenthesis, and form the first array, then within that array, use the text between [SCHOOL][/SCHOOL] for the first object, and use the text between [STATUS][/STATUS] for the second object.
Ideally, you would use something more suited to storing arrays on the server side. I would recommend JSON. This would be trivial to encode using php, and decode using javascript.
If you do not have that option server side, then you can use regex to parse your text. However, you must be sure that the contents does not have your delimiters within in it.
It is not clear how you get your target data structure from your source, but I would expect something like this might work for you:
str = "([SCHOOL] Name [/SCHOOL][STATUS] Status [/STATUS])\n\
([SCHOOL] Other name [/SCHOOL][STATUS] Other status [/STATUS])"
arr =[]
m = str.match(/\(.+?\)/g)
for(i in m){
matches = m[i].match(/\(\[SCHOOL\](.+?)\[\/SCHOOL\]\[STATUS\](.+?)\[\/STATUS\]\)/)
arr.push([matches[1],matches[2]])
}
console.dir(arr)

Javascript parse innerhtml

I have a HTML page full of data separated by commas and each row ends in a (br /) tag. In Javascript I can get this from the DOM by asking for the innerHTML of the element containing the data.
My question is how to parse the innerHTML to get the data out from between the commas and start on the next line when it hits the (br /) tag?
You can probably ignore the rest as that is my question above.
When I parse each line I will start a new object and put the data into it. I'm just not sure what to do with the innerHTML!
I did put the data through a CSVtoarray function I found but ended up with an array of one large array instead of an array of arrays for each line. I can work my way through this array creating objects from the data along the way but turning the innerHTML into a single array seems an unnecessary step when I could parse the data straight into object.
The data is put there via AJAX. I can change the format that the data comes in. As I said I have it separating data with commas and (br /) tag at the end of the line. I do not know if this is stupid or not.
So, you want to csv-parse a file where newlines are indicated with <br /> instead of \n? Just use that separator in your CSV-Parser then. Simple version:
text.split("<br />".map(function(line){ return line.split(","); })
You could also split by regular expressions, like
text.split(/\s*<br ?\/>\s*/)...
If you really habe the CSV data in a DOM, you could remove all the br-element and use the remaining (text) nodes as the lines-array.
You mention that you have control over the data you're getting via AJAX, and you're right that your current approach is not the best idea. First off, you should never try to parse HTML on your own, even if you think it's "simple" – different browsers will give you different innerHTML for the exact same content. Instead, use the DOM to find the information you're looking for.
That said, the correct approach here is just to return a JSON object from the server; you'll then have direct access to your data. Nearly every server-side language has some kind of facility to output JSON, and JavaScript can parse the JSON string natively1 with JSON.parse().
From the server, return:
{items: [
{ id: 0, name: '...' },
{ id: 1, name: '...' },
...
]}
On the client (assuming jQuery),
$.getJSON('/path-to-script/', function(d) {
for (var i = 0; i < d.items.length; i++) {
d.items[i].id;
}
});
1 - in modern browsers
You could simply do this if you just want to "get the data out from between the commas":
yourElem.innerHTML = yourElem.innerHTML.split(",").join("");
Or if you just want an array of lines:
var lines = yourElem.innerHTML.split(",");
That'll return an array of lines with <br> elements intact. It's not clear if that's what you want, though.

Categories