Table data in HTML does not separate well - html

I was working with a table in HTML and I have the following doubt: I am taking the data from a JSON array: {"key":["1","2","3"],"values":["4","5","6"]} and when trying to insert them into the table instead of putting each data in a column all the data is put in the first column, the JS code that I am using to insert the data in the table is:
var idtabla = document.getElementById("idtabla")
idtabla.innerHTML += window.location.href.split("/tabla/")[1]
function getJson(){
var id = window.location.href.split("/tabla/")[1]
var table = document.getElementById("table")
$.get( `/json`, (data) => {
if(data.error){
idtabla.innerHTML = 404 + ", tabla no encontrada"
} else {
var keys = data.key.forEach(element => {
table.innerHTML += `<tr><td>${element}</td>`
});
var values = data.values.forEach(element => {
table.innerHTML += `<td>${element}</td></tr>`
});
}
})
}
and the result it gives me is this:
How could it be solved? Thanks a lot.

There are two problems.
First, you can't add partial HTML to innerHTML like that. Whenever you assign to innerHTML, it parses the result completely. If there are any unclosed tags, they're closed automatically. If you want to build the HTML incrementally, you should do it by appending to a string, then assign the completed string to innerHTML.
Second, you're appending all the values all the values after all the keys, so they won't be in matching rows. You need to append both the key and value in the same loop. Since forEach() passes the array index to the callback function, you can use that to index into the other array.
let tableHTML = '';
data.keys.forEach((key, i) => {
tableHTML += `<tr><td>${key}</td><td>${data.values[i]}</td></tr>`;
});
table.innerHTML = tableHTML;

Related

How to view SPARQL query result as JSON objects?

I want to view SPARQL query results as JSON objects. For example, I have a RDF database where I have parents graph which includes children, relatives and their information. Is there a way to view them as JSON objects like
"Parents": {
"names": "some names"
"children":[
{"child1": {
"name": name
}}
]
.....
}
How can I achieve this? All suggestions are welcome. Thanks
SPARQL provides "application/sparql-results+json" as its document content-type for query solutions for consumption by applications that understand JSON.
In recent times I've come to realize that this aspect of SPARQL is generally understood thereby creating artificial friction for "Web Developers" who work with tools that support JSON as the default content-type for structured data.
Anyway, we recently released a HTML5, CSS, and Javascript based Single Page Application that demonstrates what's possible with SPARQL when you put its "application/results+json" query solution content-type to use. Naturally, it also provides a solution for understanding how to process JSON returned from SPARQL.
How the form works.
Code Snippet regarding JSON object handling
/*
Dynamic Table for processing JSON Structured Data (via "application/sparql-results+json" document content type)
that enables INSERT to be handled via a 3-tuple subject, predicate, object graph (relation) while query results
are handled via an N-Tuple structured table (relation).
*/
if (data.results.bindings.length > 0){
var table = tabCheckTable("dbmsTableID", "fsTableID") ; // creates table for header
var header = table.createTHead(); // creates empty tHead
var headRow = header.insertRow(0); // inserts row into tHead
var bindings = data.results.bindings;
for (var col = 0; col < data.head.vars.length; col++) { // for each column
// console.log("col = " + col)
var headCell = headRow.insertCell(col); // inserts new cell at position i in thead
headCell.innerHTML = "<b>" + data.head.vars[col] + "</b>"; // adds bold text to thead cell
}
for (i in bindings) {
// console.log("i = " + i)
var curr = 0 ; // curr is used to keep track of correct cell position
var binding = bindings[i];
var bodyRow = table.insertRow(-1); // create new row
for (n in binding) {
// console.log("n = " + n)
// console.log("curr = " + curr)
var bodyCell = bodyRow.insertCell(curr); // create new cell in row
bodyCell.innerHTML = tableFormat(binding[n].value); // set value of cell
curr += 1 ;
}
}
}
else{
throw new Error("No Data Returned");
console.log("No data returned by query");
}
})
} catch(e) {
console.error('Query Failed:', e) ;
}
}
Links
"Deceptively Simple" Data Entry Form -- this is also View-Source friendly re. all the code that drives the app
Github Repository

Use Sequelize on for loop findAll query and merge result

I'm coding opensource project in the university course
It is a function to search the value of another table by dividing input keyword by comma.
under this example data
Python,CPP,Csharp
var keyword = result[0].keyword;
var keyword_arr = [];
var keyword_split = keyword.split(',');
for (var i in keyword_split)
{
keyword_arr.push(keyword_split[i]);
}
I have succeeded in separating them with commas like above, but I'm looking for a loop in sequelize.
"Error: Can not set headers after they are sent."
An error is returned and is not executed.
I want to output the results merged. What should I do?
my code is
for (i = 0; i < keyword_arr.length; i++) {
query += models.contents.findAll({
where: {keyword: {like: '%' + keyword_arr[i] + '%'}},
raw: true
});
}
Regards.
You were in the right direction , but here it his how you can do :
queries = [];
for (i = 0; i < keyword_arr.length; i++) {
queries.push({keyword: {like: '%' + keyword_arr[i] + '%'}});
}
models.contents.findAll({
where: {
$or : queries
}
raw: true
}).then(results => {
console.log(results); // <---- Check this
})
NOTES :
models.contents.findAll() //<---- Returns promises
You can't just combine the promises by += as its not string or number
like that
In your case , it will create and run the query for each tag , so
that's not proper way of doing , you should combine the tags and create a single query as I did

Understanding ES6 tagged template literal

Following code snippet is used on Mozilla (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) to explain Tagged Template literal, please help me understand what following function is doing, i am unable to get the actual flow of the function, since they have used keys.foreach and when i inspected in Chrome, keys was a function, so not able to understand
function template(strings, ...keys) {
return (function(...values) {
var dict = values[values.length - 1] || {};
var result = [strings[0]];
keys.forEach(function(key, i) {
var value = Number.isInteger(key) ? values[key] : dict[key];
result.push(value, strings[i + 1]);
});
return result.join('');
});
}
var t1Closure = template`${0}${1}${0}!`;
t1Closure('Y', 'A'); // "YAY!"
var t2Closure = template`${0} ${'foo'}!`;
t2Closure('Hello', {foo: 'World'}); // "Hello World!"
Most of the complexity in the example comes from the overloaded function and the forEach invocation, not from the tagged template literals. It might better have been written as two separate cases:
function dictionaryTemplate(strings, ...keys) {
return function(dict) {
var result = "";
for (var i=0; i<keys.length; i++)
result += strings[i] + dict[keys[i]];
result += strings[i];
return result;
};
}
const t = dictionaryTemplate`${0} ${'foo'}!`;
t({0: 'Hello', foo: 'World'}); // "Hello World!"
function argumentsTemplate(strings, ...keys) {
is (!keys.every(Number.isInteger))
throw new RangeError("The keys must be integers");
return function(...values) {
var result = "";
for (var i=0; i<keys.length; i++)
result += strings[i] + values[keys[i]];
result += strings[i];
return result;
};
}
const t = argumentsTemplate`${0}${1}${0}!`;
t('Y', 'A'); // "YAY!"
Template is a custom function defined by us to parse the template string, whenever a function is used to parse the template stringThe first argument of a tag function contains an array of string values. The remaining arguments are related to the expressions. so here specifically we have written the function to that given output I had got confused because when in inspected keys inside the forEach, i got a function in console, but inspecting the function before forEach gave keys as the array of configurable string ${0} and ${1} in first example

assign Json value to a variable using $.each()

I am trying to pass the result of this query as a Json string to Jquery so that I can assign the value to a JQuery variable. Actually there will be more than one key:value pair but I am illustrating my problem with a single pair for simplicity. I am able to console.log the index and value however when I try to assign the value to a variable I get an "undefined" message. I have done this successfully elsewhere and am not sure what i am missing here:
$query = (
"SELECT MedCondPrimary, Count(MedCondPrimary) as Count
FROM Comments
WHERE MedCondPrimary='Arthritis'");
$result = mysqli_query($dbc, $query);
WHILE($rows = mysqli_fetch_array($result)) {
$medcond = $rows['MedCondPrimary'];
$array3[$medcond] = $rows['Count'];
};
$json_count=json_encode($array3);
echo $json_count; // {"Arthritis":"26"}
JQ:
var tally = ;
console.log(tally);// Object { Arthritis="26"} should be a string?
$.each(tally, function(index, value) {
console.log(index+":"+value); //Arthritis:26
var arthritis = value.Arthritis;
console.log(arthritis); //undefined
});
Your jQuery code should be using each() instead of $.each() here.
$( tally ).each(function( index, obj ) {
console.log( index + ":" + obj.Arthritis); // Arthritis:26
var arthritis = obj.Arthritis;
console.log( arthritis ); // 26
});
each() passes the object while $.each() passes property-value pairs for an object. You're $.each() at the other place must be working because you passed it an array as shown below:
// iterating an array
$.each( [{Arthritis:26}], function( index, obj) {
console.log( obj.Arthritis ); // 26
});
PHP Edit :
$json_count=json_encode($array3);
echo "[" . $json_count . "]";

Javascript: Using reviver function, I seem can't get to alter all the keys, while concating the numbers

I just want to change all the keys in batchesX. But I can't seem to alter all keys, because of concat. This is what I learned from post.
Please advise how I can change all keys with numbers.
var batchesX = '[{"batch":"0010002033"},{"batch":"0010001917"},{"batch":"0000020026"},{"batch":"0000017734"},'+
'{"batch":"0000015376"},{"batch":"0000014442"},{"batch":"0000014434"},{"batch":"0000014426"},'+
'{"batch":"0000013280"},{"batch":"0000012078"},{"batch":"0000012075"},{"batch":"0000012072"},'+
'{"batch":"0000011530"},{"batch":"0000011527"},{"batch":"0000011342"},{"batch":"0000010989"},'+
'{"batch":"0000010477"},{"batch":"0000008097"},{"batch":"0000007474"},{"batch":"0000006989"},'+
'{"batch":"0000004801"},{"batch":"0000003566"},{"batch":"0000003565"},{"batch":"0000001392"},'+
'{"batch":"0000001391"},{"batch":"0000000356"},{"batch":"0000"},{"batch":"000"},{"batch":""},'+
'{"batch":null}]'; // 30 elements
//in JSON text
var batchi = "batch";
var obj_batchesY = JSON.parse(batchesX);
console.debug(obj_batchesY);
var obj_batchesYlength = obj_batchesY.length;
console.debug(obj_batchesYlength);
var obj_batchesX = JSON.parse(batchesX,
function(k,v)
{
for(var i=1; i <= obj_batchesYlength; i++ )
{
if(k=="batch")
{
this.batchi.concat(string(i)) = v;
}
else
return v;
}
}
);
console.debug(obj_batchesX);
Is the code too long winded?
Many thanks in advance.
Clement
The return value of the reviver function only replaces values. If you need to replace keys, then use stringify and replace before the parse call, like this:
JSON.parse(JSON.stringify({"alpha":"zulu"}).replace('"alpha":','"omega":'))
Here is how to replace all numeric keys:
function newkey()
{
return Number(Math.random() * 100).toPrecision(2) + RegExp.$1
}
//Stringify JSON
var foo = JSON.stringify({"123":"ashanga", "12":"bantu"});
//Replace each key with a random number without replacing the ": delimiter
var bar = foo.replace(/\d+("?:)/g, newkey)
//Parse resulting string
var baz = JSON.parse(bar);
Make sure each replaced key is unique, since duplicate keys will be removed by the parse method.