Accessing property's array with a specific id - javascript

What i wanted to do is access random property for example let1, let2 with their first string in array which is ID "1" , "2" , "3" , "4" , "5".
brojleta is actually that ID i mentioned before, it is different from id down there(var id = item[0][1]). What i need is to get all other strings based on their ID. I tried it like this :
var data = {
let1:[["1","2","10.2.2019.","11.2.2019.","Beograd Aerodrom","Amsterdam Aerodrom","30","12000"]],
let2:[["2","4","15.2.2019.","16.2.2019","Amsterdam Aerodrom","Rim Aerodrom","30","8000"]],
let3:[["3","6","25.2.2019.","28.2.2019.","Rim Aerodrom","Beograd Aerodrom","30","8000"]],
let4:[["4","8","13.2.2019.","14.2.2019.","Beograd Aerodrom","Moskva Aerodrom","30","13000"]],
let5:[["5","10","1.3.2019.","4.3.2019.","Beograd Aerodrom","New York Aerodrom","30","18000"]]
};
function getParamValue(brojleta) {
var location = decodeURI(window.location.toString());
var index = location.indexOf("?") + 1;
var subs = location.substring(index, location.length);
var splitted = subs.split("&");
for (i = 0; i < splitted.length; i++) {
var s = splitted[i].split("=");
var pName = s[0];
var pValue = s[1];
if (pName == brojleta) {
return pValue;
}
}
}
var brojleta = getParamValue("id");
var item = data.find(item => item[0][0] === brojleta);
var id = item[0][1]
var datumpolaska = item[0][2]
var datumdolaska = item[0][3]
var polazniaerodrom = item[0][4]
var dolazniaerodrom = item[0][5]
var brojsedista = item[0][6]
var cenakarte = item[0][7]
var data1 = data.let1[0];
var data2 = data.let2[0];
var data3 = data.let3[0];
var data4 = data.let4[0];
var data5 = data.let5[0];
/* this is the code for adding data from array to table */
$(document).ready(function(){
var row1cells = $("#row1 td");
var row2cells = $("#row2 td");
var row3cells = $("#row3 td");
var row4cells = $("#row4 td");
var row5cells = $("#row5 td");
for (var index=0; index<8; index++) {
$(row1cells[index]).html(data1[index]);
$(row2cells[index]).html(data2[index]);
$(row3cells[index]).html(data3[index]);
$(row4cells[index]).html(data4[index]);
$(row5cells[index]).html(data5[index]);
}
});

To make your code work you should choose variable data to be an array of arrays instead of an object. Then you can run var item = data.find(item => item[0] === brojleta); and similar operations.
It would look like this:
var data = [["1","2","10.2.2019.","11.2.2019.","Beograd Aerodrom","Amsterdam Aerodrom","30","12000"],
["2","4","15.2.2019.","16.2.2019","Amsterdam Aerodrom","Rim Aerodrom","30","8000"],
["3","6","25.2.2019.","28.2.2019.","Rim Aerodrom","Beograd Aerodrom","30","8000"],
["4","8","13.2.2019.","14.2.2019.","Beograd Aerodrom","Moskva Aerodrom","30","13000"],
["5","10","1.3.2019.","4.3.2019.","Beograd Aerodrom","New York Aerodrom","30","18000"]];

I think you really want this:
Remove the || 3 // test #3 after testing
Try removing the 3 from the input and click search too
var data = {
let1:[["1","2","10.2.2019.","11.2.2019.","Beograd Aerodrom","Amsterdam Aerodrom","30","12000"]],
let2:[["2","4","15.2.2019.","16.2.2019","Amsterdam Aerodrom","Rim Aerodrom","30","8000"]],
let3:[["3","6","25.2.2019.","28.2.2019.","Rim Aerodrom","Beograd Aerodrom","30","8000"]],
let4:[["4","8","13.2.2019.","14.2.2019.","Beograd Aerodrom","Moskva Aerodrom","30","13000"]],
let5:[["5","10","1.3.2019.","4.3.2019.","Beograd Aerodrom","New York Aerodrom","30","18000"]]
};
function getParamValue(brojleta) {
return new URLSearchParams(document.location.search.substring(1)).get(brojleta)
}
function show(item) {
$tr = $("<tr/>"), $tbd = $("#tbd");
$.each(item,function(_,fld) {
$tr.append("<td>"+fld+"</td>");
})
$tr.appendTo($tbd);
}
function showAll() {
Object.keys(data).forEach(function(key) {
show(data[key][0]);
})
}
$(function() {
$("#search").on("click",function() {
$("#tbd").empty();
var brojleta = $("#broj_leta").val();
if (brojleta) show(data["let"+brojleta][0])
else showAll();
});
var brojleta = getParamValue("id") || 3 // test #3
if (brojleta) $("#broj_leta").val(brojleta);
$("#search").trigger("click");
})
th, td { border:1px solid lightgrey; padding: 3px }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="broj_leta" /><button id="search">Search</button>
<table>
<thead>
<tr>
<th>id</th>
<th>Datumpolaska</th>
<th>Datumdolaska</th>
<th>Plazniaerodrom</th>
<th>Dolazniaerodrom</th>
<th>Brojsedista</th>
<th>Cenakarte</th>
</tr>
</thead>
<tbody id="tbd">
</tbody>
</table>

You can first filter the data based on ID and then map your required variable to final output array in below code output.
var brojleta = 1;
const mappedarray = Object.entries(data).filter((k,v)=>{return k[0] == "let"+brojleta});
console.log(mappedarray[0][1][0]);

You can use the lodash function find().
This is the same function as Array.find but it works on Object.
https://lodash.com/docs/4.17.11#find

Related

Array object value not counting up in js

I have a problem of some of my object values in my array do not show correct in my html site, it only shows the last number of the array in every .When i make a console log it shows the correct numbers its just in the table it wont do it. it did work before but now i doest not and i do not know what i did that ruined my code. I hope for some quick help that works.
function metric(tryk){
for (var i = 0; i < death_row.length; i++) {
if (tryk === "metric"){
var testMetric = death_row[i].height;
}
if (testMetric === null){
death_row[i].height = 0;
death_row[i].weight = 0;
} else{
var klip1 = death_row[i].height.slice(0,1);
var klip2 = death_row[i].height.slice(3,death_row[i].height.indexOf("'",i+2));
var klip2tal = Number(klip2);
//console.log(klip2);
var regn1 = klip1 * 12;
var regn2 = regn1 + klip2tal;
var regn3 = regn2 * 2.54;
console.log(regn3);
var vaegt = death_row[i].weight/2.2046;
console.log(vaegt);
};
};
var tabel2 = "<table>";
for (var i = 0; i < death_row.length; i++) {
tabel2+="<tr>";
tabel2+="<td>"+death_row[i].first_name +" "+ death_row[i].last_name+"</td>";
tabel2+="<td>"+death_row[i].age_at_execution+" år"+"</td>";
tabel2+="<td>"+regn3+"</td>";
tabel2+="<td>"+vaegt+"</td>";
tabel2+="</tr>";
}
tabel2+="</table>";
document.getElementById("test").innerHTML = tabel2;
};
<div id="test"></div>
<div id="test2"></div>
Assuming that death_row is globally available and you want to have unique values for regn3 and vaegt, you'll need to save those to the individual row objects too.
var regn3 = regn2 * 2.54;
death_row[i].regn3 = regn3;
var vaegt = death_row[i].weight/2.2046;
death_row[i].vaegt = vaegt;
Then you can address them in your table the same way you display the other row values:
tabel2+="<td>"+death_row[i].regn3+"</td>";
tabel2+="<td>"+death_row[i].vaegt+"</td>";
You can construct HTML elements and add them to the document this way.
A for...of loop can set the innerHTML (or any property) of the elements as desired, using data from your array.
const death_row = [
{ first_name: "first1", last_name: "last1", age_at_execution: "age1" },
{ first_name: "first2", last_name: "last2", age_at_execution: "age2" },
{ first_name: "first3", last_name: "last3", age_at_execution: "age3" }
];
const tabel2 = document.createElement("table");
for (let person of death_row) {
let regn3 = "regn3 goes here"
let vaegt = "vaegt goes here"
const row = document.createElement("tr");
const nameCell = document.createElement("td");
nameCell.innerHTML = person.first_name + " " + person.last_name;
row.appendChild(nameCell);
const ageCell = document.createElement("td");
ageCell.innerHTML = person.age_at_execution + " år";
row.appendChild(ageCell);
const regn3Cell = document.createElement("td");
regn3Cell.innerHTML = regn3;
row.appendChild(regn3Cell);
const vaegtCell = document.createElement("td");
vaegtCell.innerHTML = vaegt;
row.appendChild(vaegtCell);
tabel2.appendChild(row);
}
document.getElementById("test").appendChild(tabel2);
td{ border: 1px solid gray; padding: 5px; }
<div id="test"></div>

Unable to parse json using javascript

I have a json which i'm trying to parse it using javascript. Iteration count and the pages getting appended to it are going to be dynamic.
Expected Result
Just like the above image i'm able to take dynamic iteration keys from the below mentioned json.
Iteration.json
{
"count":[
{
"iteration1":[
{
"PageName":"T01_Launch"
},
{
"PageName":"T02_Login"
}
]
},
{
"iteration2":[
{
"PageName":"T01_Launch"
},
{
"PageName":"T02_Login"
}
]
}
]
}
When i click on iteration it has to populate the corresponding pagenames for that particular iteration as shown in expected result image. But what i get actually is (refer the image below):
Please find the code that i tried:
var pagenamearray = [];
$.getJSON("iteration.json", function(json) {
var hits = json.count;
var iterations, tnname, iteration;
for (var k in hits) {
var value;
if (hits.hasOwnProperty(k)) {
value = hits[k];
var iteratearray = [];
for (var j in value) {
if (value.hasOwnProperty(j)) {
j;
var check = value[j];
for (var i in check) {
if (check.hasOwnProperty(i)) {
var test = check[i];
for (var t in test) {
if (test.hasOwnProperty(t)) {
var pagename = JSON.stringify(t)
var arr = []
if (pagename.includes("PageName")) {
//alert("Key is " +pagename + ", value is" + JSON.stringify(test[t]));
for (var it = 0; it < hits.length; it++) {
if ((Object.keys(hits[it])).includes(j)) {
var pagenamevalue = test[t];
arr[it] = [];
arr.push(pagenamevalue);
}
}
}
//alert(arr)
}
pagenamearray.push(arr);
}
}
}
}
var row = document.createElement('div');
row.setAttribute("class", "row");
row.setAttribute("id", j)
var gridWidth = document.createElement('div');
gridWidth.setAttribute("class", "col-lg-12");
var panelRoot = document.createElement('div');
panelRoot.setAttribute("class", "panel panel-default");
var panelHeading = document.createElement('div');
panelHeading.setAttribute("class", "panel-heading");
var heading3 = document.createElement('a');
heading3.setAttribute("class", "panel-title");
var icon = document.createElement('i');
icon.setAttribute("class", "fa fa-long-arrow-right fa-fw");
heading3.appendChild(icon);
heading3.innerHTML = j;
heading3.setAttribute("onclick", "doit('" + j + "');");
panelHeading.appendChild(heading3);
/* var panelBody=document.createElement('div');
panelBody.setAttribute("class","panel-body");
panelBody.setAttribute("id","panellinks");*/
panelRoot.appendChild(panelHeading);
// panelRoot.appendChild(panelBody)
gridWidth.appendChild(panelRoot);
row.appendChild(gridWidth);
document.getElementById("analysis").appendChild(row);
}
}
}
});
function doit(value) {
var ul = document.getElementById(value);
if (ul != undefined) {
$("#" + "expandlinks").remove();
$("#" + value + value).remove();
}
var accordion = document.getElementById(value);
var panelBody = document.createElement('div');
panelBody.setAttribute("class", "panel-body");
panelBody.setAttribute("id", "expandlinks")
var tablediv = document.createElement('div')
var tablelink = document.createElement('a');
tablediv.appendChild(tablelink);
var graphdiv = document.createElement('div')
var graphlink = document.createElement('a');
graphdiv.appendChild(graphlink);
var recommndiv = document.createElement('div');
var recommendlink = document.createElement('a');
recommndiv.appendChild(recommendlink)
//alert(pagenamearray.length)
tablelink.innerHTML = pagenamearray;
/*graphlink.innerHTML="Timeline View";
recommendlink.innerHTML="Recommendations";*/
panelBody.appendChild(tablediv);
panelBody.appendChild(recommndiv);
panelBody.appendChild(graphdiv);
accordion.appendChild(panelBody);
}
Any advise on how to achieve this would be of great help. Thanks in advance.
I think the problem is how you assign the pagenamearray to tablelink.innerHTML. This converts the array to a string, converting all elements in the array to a string too and separating them by a comma each. However, your pagenamearray contains some empty arrays too; these will convert to an empty string in the process, but will still have a comma before and after them.
In your example code above, the pagenamearray will end up with a value of [[[],"T01_Launch"],[[],"T02_Login"],[null,[],"T01_Launch"],[null,[],"T02_Login"]] - when converted to a String, this will result in ",T01_Launch,,T02_Login,,,T01_Launch,,,T02_Login". So instead of assigning it to the innerHTML value directly, you'll first have to filter out the empty arrays and null values.

dynamic generated html via jQuery is not working

i m generating dynamic html through jquery, when i am using rowspan than it is not working fine.
Expected output:
My Current code:
var shopTimeArray = ["10:00:00","10:15:00","10:30:00","10:45:00","11:00:00"];
var workernames = ["Kapper 1","Kapper 2"];
var workerids = ['148','196'];
var workerTimes = [];
workerTimes['148'] = ["10:00:00","10:15:00","10:30:00","10:45:00","11:00:00"];
workerTimes['196'] = ["10:00:00","10:15:00","10:30:00","10:45:00","11:00:00"];
var workerAppointments = [];
workerAppointments['148'] = ["10:00:00","10:15:00","10:30:00","10:45:00"];
workerAppointments['196'] = ["10:30:00","10:45:00"];
var appointmentTime = [];
appointmentTime['148'] = ["10:00:00"];
appointmentTime['196'] = ["10:15:00"];
var $elem = $("<table>",{'class':'table table-responsive table-bordered overview-table','border':'1'});
var $thead = $('<thead>',{}).appendTo($elem);
var $theadTR = $("<tr>",{}).appendTo($thead);
$("<th>",{'width':'50','html':'Tijd'}).appendTo($theadTR);
$.each(workernames,function(i)
{
$("<th>",{'html':workernames[i]}).appendTo($theadTR);
});
var $tbody = $("<tbody>",{'class':'overview_table_td'}).appendTo($elem);
$rowspan = 0;
$.each(shopTimeArray,function(i)
{
$tbodyTR = $("<tr>",{}).appendTo($tbody);
$tbodyTH = $("<th>",{'scope':'row','html':shopTimeArray[i].slice(0,-3)}).appendTo($tbodyTR);
$.each(workerids,function(j)
{
if(typeof(workerTimes[workerids[j]]) != "undefined" && $.inArray(shopTimeArray[i],workerTimes[workerids[j]]) !== -1 )
{
//console.log(appointmentTime[workerids[j]]);
if(shopTimeArray[i] == appointmentTime[workerids[j]])
{
$.each(workerAppointments[workerids[j]],function(y){
$rowspan++;
});
html = "appointment"+j;
} else {
html = '';
}
$tbodyTD = $("<td>",{'html':html,'rowspan':$rowspan}).appendTo($tbodyTR);
}
});
});
$(".overview-table").html($elem);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="overview-table">
</div>
i tried with the solution like
if($rowSpan > 0) {
$rowSpan--;
} else {
add td
}
but above code is not working properly.
i want to omit the cells which are in the workerAppointments variable,
currently it is looking wearied,
Looking for help.

Hide the div elements if not including specific keywords

I have seen a brunch of solution about how to show/hide the div which do not contains(or contains) specific keywords but none of them do help.
So far I have done some codes like this:
<div class="media">Title : orange</div>
<div class="media">this is something about orangessss yolo</div>
<div class="media">Title : apple</div>
<div class="media">this is something about apple yolo</div>
<button id="filter">test</button>
And I have a method to fliter the elements:
var KeywordArr = ["orange","orangessss"];
$('#filter').click(function () {
var key = $(".media");
var word= key.find(".media").html();
if(!word && word.toLowerCase().match([KeywordArr])) {
$(".media").css("display", "none");
}
});
These codes suppose to add "display:none" to every "media" class which does not contains any keywords included in the array. But it's not working as my exception.
So how can I hide all the elements when the "< div"> do not have the value contain in keywordArr?
Solution:
$('#filter').click(function () {
var elems = $(".media");
var KeywordArr = ["orange", "orangessss"];
var res = $();
for (var i = 0; i < KeywordArr.length; i++) {
res = res.add(elems.filter(":contains('" + KeywordArr[i] + "')"));
}
elems.not(res).hide();
});
Try to use :contains() selector at this context,
var elems = $(".media");
var KeywordArr = ["orange", "orangessss"];
var res = $();
for (var i = 0; i < KeywordArr.length; i++) {
res = res.add(elems.filter(":contains('" + KeywordArr[i] + "')"));
}
elems.not(res).hide();
Also note that contains selector is case sensitive.
DEMO
To keep your code more declarative you can use array foreach. also make sure to keep you variable names all lowercase.
var elems = $(".media");
var keywordArr = ["orange", "orangessss"];
var res = $();
keywordArr.forEach(function(keyword){
res = res.add(elems.filter(":contains('" + keyword + "')"));
});
elems.not(res).hide();
Also if you can write the Same code with ES6 Template literals, here is a link to Demo
const elems = $(".media");
const keywordArr = ["orange", "orangessss"];
let res = $();
keywordArr.forEach(
(keyword) => res = res.add(elems.filter(`:contains(${keyword})`))
);
elems.not(res).hide();

how to get difference of 2 columns in dynamically created rows in javascript

I have a dynamically created table having 3 columns. I need the difference of Col 2 and Col 1 to be populated in Col 3. I have no clue as to how to proceed with dynamically created tables. I'm reading the table values in my save function. Can you please suggest as to how to include the code for the difference?
JS:
function save()
{
var eval_tbl = document.getElementById('bagger_reading_list');
var eval_row_array = [];
for (i=0; i<eval_tbl.rows.length; i++)
{
var tableRow = {
Start_Reading : eval_tbl.rows[i].cells[1].firstElementChild.value,
End_Reading : eval_tbl.rows[i].cells[2].firstElementChild.value,
Total_Reading : eval_tbl.rows[i].cells[3].firstElementChild.value, \\ I need the difference of End-Reading - Start_Reading to be displayed on Total_Reading of eah row created.
}
eval_row_array[eval_row_array.length] = tableRow;
}
}
Convert the values into Float (just to be safe) using parseFloat() and add it up. Do it like:
Total_Reading : parseFloat(eval_tbl.rows[i].cells[2].firstElementChild.value) - parseFloat(eval_tbl.rows[i].cells[1].firstElementChild.value),
So, your save function should look like:
function save()
{
var eval_tbl = document.getElementById('bagger_reading_list');
var eval_row_array = [];
for (i=0; i<eval_tbl.rows.length; i++)
{
var tableRow = {
Start_Reading : eval_tbl.rows[i].cells[1].firstElementChild.value,
End_Reading : eval_tbl.rows[i].cells[2].firstElementChild.value,
Total_Reading : parseFloat(eval_tbl.rows[i].cells[2].firstElementChild.value) - parseFloat(eval_tbl.rows[i].cells[1].firstElementChild.value)
}
eval_row_array[eval_row_array.length] = tableRow;
}
}
Readup: parseFloat() | MDN
Try this:
function save()
{
var eval_tbl = document.getElementById('bagger_reading_list');
var eval_row_array = [];
for (i=0; i<eval_tbl.rows.length; i++)
{
var startReading = eval_tbl.rows[i].cells[1].firstElementChild.value;
var endReading = eval_tbl.rows[i].cells[2].firstElementChild.value;
var totalReading = parseFloat(endReading) - parseFloat(startReading);
var tableRow = {
Start_Reading : startReading,
End_Reading : endReading,
Total_Reading : totalReading
}
eval_row_array[eval_row_array.length] = tableRow;
}
}
I have written a small code. Check if it fits your need
function saved()
{
var eval_tbl = document.getElementById('Table');
var eval_row_array = [];
for (i=0; i<eval_tbl.rows.length; i++)
{
var tableRow = {
Start_Reading : eval_tbl.rows[i].cells[0].innerHTML,
End_Reading : eval_tbl.rows[i].cells[1].innerHTML,
Total_Reading :parseInt(eval_tbl.rows[i].cells[0].innerHTML) - parseInt(eval_tbl.rows[i].cells[1].innerHTML)
}
eval_tbl.rows[i].cells[2].innerHTML=parseInt(eval_tbl.rows[i].cells[0].innerHTML) - parseInt(eval_tbl.rows[i].cells[1].innerHTML)
eval_row_array[eval_row_array.length] = tableRow;
}
}

Categories

Resources