Output array to element classes - javascript

I'm trying to output a JSON object to different parts of an HTML page using the same classes.
I'm importing my JSON from an API but when I've put information into it (via input fields) it looks a little bit like this:
{
"trip": [
{ // the first object in the trip-array
"leg": [{
"tripid": "0",
"origin": {
"name": "New York",
"time": "12:04"
},
"destination": {
"name": "Albany",
"time": "1:49"
}
},{
"tripid": "1",
"origin": {
"name": "Albany",
"time": "2:05"
},
"destination": {
"name": "Boston",
"time": "3:12"
}
}]
},
{ // the second object in the trip-array
"leg": [{
"tripid": "0",
"origin": {
"name": "New York",
"time": "1:04"
},
"destination": {
"name": "Albany",
"time": "2:49"
}
},{
"tripid": "1",
"origin": {
"name": "Albany",
"time": "3:05"
},
"destination": {
"name": "Boston",
"time": "4:12"
}
}]
}]
}
I'm trying to display the information on my website, but I can't get it to behave the way I want it to.
The first time around I did it something like this (after fetching the JSON via my PHP-page):
function addDataToHTML(data){
var trips = data.trip;
$.each(trips, function(){
document.getElementById('show_all_results');
var summary = document.createElement('div');
summary.innerHTML = "<span class='origin_time'>" + this.leg[0].origin.time +
" </span><span class='origin_name'> " + this.leg[0].origin.name +
"</span><span>-</span><span class='destination_time'>" + this.leg[leg.length-1].destination.time +
" </span><span class='destination_name'> " + this.leg[this.leg.length-1].destination.name +
"</span>";
document.getElementById('show_all_results').appendChild(summary);
});
}
This works but the problem I'm having is that I want to add a button in the code which would give me more information via a display:block/none-functionality. The button (and the rest of the information) would be created similarly with me having to write it in the innerHTML part of the JS, but all the ways that I've tried haven't worked and I guess it's all about me creating the divs and other DOM objects in the JS code which means that the HTML doesn't really recognize them.
Anyhow, to get more control of the code I'm now trying something like this with the HTML:
<div id="show_all_results">
<div id='search_result_single'> // First results....
<div id='search_result_from_box'>
<span class="origin_time"></span>
<span class="origin_name"></span>
</div>
<div id='search_result_divider'>
<span>-</span>
</div>
<div id='search_result_to_box'>
<span class='destination_time'></span>
<span class='destination_name'></span>
</div>
</div>
<div id='search_result_single'> // Second results....
<div id='search_result_from_box'>
<span class="origin_time"></span>
<span class="origin_name"></span>
</div>
<div id='search_result_divider'>
<span>-</span>
</div>
<div id='search_result_to_box'>
<span class='destination_time'></span>
<span class='destination_name'></span>
</div>
</div>
...and so on.
</div>
The JS:
for (var i = 0; i < this.leg.length; i++) {
var originName = document.getElementsByClassName("origin_name");
var originTime = document.getElementsByClassName("origin_time");
var destTime = document.getElementsByClassName("destination_time");
var destName = document.getElementsByClassName("destination_name");
for (var x = 0; x < originName.length; x++) {
var originNameItem = originName[x];
originNameItem.innerHTML = this.leg[0].origin.name;
}
for (var y = 0; y < originTime.length; y++) {
var originTimeItem = originTime[y];
originTimeItem.innerHTML = this.leg[i].origin.time;
}
for (var z = 0; z < destTime.length; z++) {
var destTimeItem = destTime[z];
destTimeItem.innerHTML = this.leg[this.leg.length - 1].destination.time;
}
for (var a = 0; a < destName.length; a++) {
var destNameItem = destName[a];
destNameItem.innerHTML = this.leg[this.leg.length - 1].destination.name;
}
}
Is there anybody that can help me get each part of the leg-array into different parts of the page using the same classes as I've done? Or is there a better way?
This became really long, sorry about that, but please let me know if I can provide any additional information. Thanks!

Related

Loading from json into HTML/JavaScript

so I am doing a small project in which I need to put some data about products into a json file, and then load that data into the JavaScript section of the html code. The problem is that I keep getting errors like Microsoft Visual Code is telling me that the object I am trying to load is underfined.
Here is my JSON file:
{
"Data" :
[
{"Name": "Widget", "Price": 25.00, "Quantity": 5 },
{"Name": "Thing", "Price": 15.00, "Quantity": 5 },
{"Name": "Doodad", "Price": 5.00, "Quantity": 10 }
]
}
And here is my code from the HTML page.
<form id="form1">
What product do you wish to search for? <input name="name" type="text" size="20">
</form>
<button onclick="outputprodus()">Submit
</button>
<script type="text/javascript" src="Vlad.json"></script>
<script>
var userdata = JSON.parse(Data);
var produs1_nume = userdata[0].Name;
var produs1_pret = userdata[0].Price;
var produs1_cantitate = userdata[0].Quantity;
function outputprodus(){
var x, y;
x=document.getElementById("form1");
y=x.elements["name"].value;
document.write(y+" este produsul cautat.");
document.write("<br>");
document.write(produs1_nume+" costa "+produs1_pret+" pentru "+produs1_cantitate+" bucati");
}
</script>
Am I loading the data wrong, or making some mistake afterwards?
You were loading json as script.
Here is how to load a file from network.
Codepen: https://codepen.io/kishin-karra/pen/ExVqzRw?editors=1010
var userdata = null;
var produs1_nume = null;
var produs1_pret = null;
var produs1_cantitate = null;
fetch('https://s3.ap-south-1.amazonaws.com/com.instadl.test-assets-123/Vlad.json').then(res => {
res.json().then((data) => {
userdata = data.Data;
produs1_nume = userdata[0].Name;
produs1_pret = userdata[0].Price;
produs1_cantitate = userdata[0].Quantity;
})
})
function outputprodus() {
var x, y;
x = document.getElementById("form1");
y = x.elements["name"].value;
document.write(y + " este produsul cautat.");
document.write("<br>");
document.write(produs1_nume + " costa " + produs1_pret + " pentru " + produs1_cantitate + " bucati");
}

Randomising array from a matrix (bidimensional array)

I Currently have the following matrix
const fileName = [
["a01", "b01", "c01", "d01", "e01", "f01", "g01", "h01", "i01", "j01", "k01", "l01"],
["a02", "b02", "c02", "d02", "e02", "f02", "g02", "h02", "i02", "j02", "k02", "l02"],
["a03", "b03", "c03", "d03", "e03", "f03", "g03", "h03", "i03", "j03", "k03", "l03"],
["a04", "b04", "c04", "d04", "e04", "f04", "g04", "h04", "i04", "j04", "k04", "l04"],
["a05", "b05", "c05", "d05", "e05", "f05", "g05", "h05", "i05", "j05", "k05", "l05"],
["a06", "b06", "c06", "d06", "e06", "f06", "g06", "h06", "i06", "j06", "k06", "l06"],
["a07", "b07", "c07", "d07", "e07", "f07", "g07", "h07", "i07", "j07", "k07", "l07"],
["a08", "b08", "c08", "d08", "e08", "f08", "g08", "h08", "i08", "j08", "k08", "l08"],
["a09", "b09", "c09", "d09", "e09", "f09", "g09", "h09", "i09", "j09", "k09", "l09"],
["a10", "b10", "c10", "d10", "e10", "f10", "g10", "h10", "i10", "j10", "k10", "l10"],
["a11", "b11", "c11", "d11", "e11", "f11", "g11", "h11", "i11", "j11", "k11", "l11"],
["a12", "b12", "c12", "d12", "e12", "f12", "g12", "h12", "i12", "j12", "k12", "l12"]
];
and I create a new array with filenames from it randomising 1 item of each subarray using this function:
function randomise() {
let sequence = fileName.map(option => {
const random = Math.floor(Math.random() * 11);
return option[random];
});
let randomSelection = sequence.map(createURL);
function createURL(fileName) {
return `assets/music/${fileName}.mp3`;
}
console.log(randomSelection);
}
So I get an array such as:
["assets/music/f01.mp3", "assets/music/f02.mp3", "assets/music/b03.mp3", "assets/music/k04.mp3", "assets/music/b05.mp3", "assets/music/f06.mp3", "assets/music/i07.mp3", "assets/music/d08.mp3", "assets/music/d09.mp3", "assets/music/g10.mp3", "assets/music/a11.mp3", "assets/music/d12.mp3"]
But I want to rearrange my matrix in this way:
const fileName = [
["a01", "a02", "a03", "a04", "a05", "a06", "a07", "a08", "a09", "a10", "a11", "a12"],
["b01", "b02", "b03", "b04", "b05", "b06", "b07", "b08", "b09", "b10", "b11", "b12"],
["c01", "c02", "c03", "c04", "c05", "c06", "c07", "c08", "c09", "c10", "c11", "c12"],
["d01", "d02", "d03", "d04", "d05", "d06", "d07", "d08", "d09", "d10", "d11", "d12"],
["e01", "e02", "e03", "e04", "e05", "e06", "e07", "e08", "e09", "e10", "e11", "e12"],
["f01", "f02", "f03", "f04", "f05", "f06", "f07", "f08", "f09", "f10", "f11", "f12"],
["g01", "g02", "g03", "g04", "g05", "g06", "g07", "g08", "g09", "g10", "g11", "g12"],
["h01", "h02", "h03", "h04", "h05", "h06", "h07", "h08", "h09", "h10", "h11", "h12"],
["i01", "i02", "i03", "i04", "i05", "i06", "i07", "i08", "i09", "i10", "i11", "i12"],
["j01", "j02", "j03", "j04", "j05", "j06", "j07", "j08", "j09", "j10", "j11", "j12"],
["k01", "k02", "k03", "k04", "k05", "k06", "k07", "k08", "k09", "k10", "k11", "k12"]
];
I need to randomly select 1 item from each of the indexes of those subarrays, so one random item ending with "1", another ending with "2", etc
Could you help me please? Thanks!
If these are the actual values of the array you're using, you can just loop from 1 through 12 and stick it together with a random character from the string "abcdefghijk" using randojs' rando() function (or otherwise if you prefer).
for(var i = 1; i <= 12; i++){
console.log("assets/music/" + rando("abcdefghijk") + (i < 10 ? "0" : "") + i + ".mp3")
}
<script src="https://randojs.com/1.0.0.js"></script>
This code uses randojs.com to simplify the randomness and make it easier to read, so if you want to use this code, make sure this is in the head tag of your html document:
<script src="https://randojs.com/1.0.0.js"></script>
To answer the second part of your question (which you posted as another answer to this question), you don't need to keep your fileName variable to construct the HTML here if you'd rather not. You can do it like this instead:
var letters = "abcdefghijk";
for(var i = 0; i < letters.length; i++){
var musicRowID = letters.charAt(i) + "01";
$("#music-grid").append(`<div id="music-row-${musicRowID}" class="row no-gutters"></div>`);
for(var j = 1; j <= 12; j++){
var columnID = letters.charAt(i) + (j < 10 ? "0" : "") + j;
$(`#music-row-${musicRowID}`).append(`<div class="col-1"><button id="${columnID}" class="btn bar song">${columnID.toUpperCase()}</button></div>`);
}
}
Very beautiful Aaron! I created the array like this:
let randomSelection = new Array();
function randomise() {
for (let i = 1; i <= 12; i++) {
let index = `assets/music/${rando("abcdefghijkl")}${i < 10 ? "0" : ""}${i}.mp3`;
randomSelection.push(index);
}
}
randomise()
The only problem now is that I was using the code below to populate a grid based in my fileName variable...
fileName.forEach(row => {
$("#music-grid").append(`<div id="music-row-${row.slice(0, 1)}" class="row no-gutters"></div>`);
row.forEach(col => {
$(`#music-row-${row.slice(0, 1)}`).append(
`<div class="col-1"><button id="${col}" class="btn bar song">${col.toUpperCase()}</button></div>`
);
});
});
Do you reckon it is better to keep my original fileName variable in order to allow it to populate the grid?
Thanks so much!
If I understood you correctly this will give you your desired output. Picking one letter for each number. Hope this helps for whatever you need it.
const fileName = [
["a01", "a02", "a03", "a04", "a05", "a06", "a07", "a08", "a09", "a10", "a11", "a12"],
["b01", "b02", "b03", "b04", "b05", "b06", "b07", "b08", "b09", "b10", "b11", "b12"],
["c01", "c02", "c03", "c04", "c05", "c06", "c07", "c08", "c09", "c10", "c11", "c12"],
["d01", "d02", "d03", "d04", "d05", "d06", "d07", "d08", "d09", "d10", "d11", "d12"],
["e01", "e02", "e03", "e04", "e05", "e06", "e07", "e08", "e09", "e10", "e11", "e12"],
["f01", "f02", "f03", "f04", "f05", "f06", "f07", "f08", "f09", "f10", "f11", "f12"],
["g01", "g02", "g03", "g04", "g05", "g06", "g07", "g08", "g09", "g10", "g11", "g12"],
["h01", "h02", "h03", "h04", "h05", "h06", "h07", "h08", "h09", "h10", "h11", "h12"],
["i01", "i02", "i03", "i04", "i05", "i06", "i07", "i08", "i09", "i10", "i11", "i12"],
["j01", "j02", "j03", "j04", "j05", "j06", "j07", "j08", "j09", "j10", "j11", "j12"],
["k01", "k02", "k03", "k04", "k05", "k06", "k07", "k08", "k09", "k10", "k11", "k12"]
];
let pickedValues = [];
for (i = 0; i <= fileName.length; i++) {
let index = Math.floor(Math.random() * ((fileName.length - 1) - 0 + 1));
pickedValues[i] = (fileName[index][i]);
}
console.log(pickedValues);

How to make Excel file that has been converted to JSON load to table (DataTables) automatically

so i got this assigment, i need to load CSV file into html page,
after i loaded it, i need to make a code that run automatically -
getting the object field name - put it in the table head, and the match the value to each of the object field name.
everything neeed to be automtically (because our teacher is going to check just by adding the csv file - nothing can be hard coded.
we also need to use library called Data Tables.
i managed to do some of the assigment, but most of it is hard coded so it is not good.
here is my html -
<table id="table_id" class="display">
<thead>
<tr id="FieldNames">
</tr>
</thead>
<tbody id="Values">
</tbody>
</table>
and to thid table i added this code -
(with hard coded JSON just to see if i can do it before i import CSV file)
const Json =
[
{
"name": "john",
"age": 35,
"email": "AF#asdsa.com",
"address": "Rishon LeZion"
},
{
"name": "hezi",
"age": 31,
"email": "wertwree#grf.com",
"address": "Rishon LeZion"
},
{
"name": "david",
"age": 23,
"email": "wertewrt#fd.com",
"address": "Rishon LeZion"
},
{
"name": "jacky",
"age": 41,
"email": "wertr#aa.com",
"address": "Rishon LeZion"
}];
$(document).ready(function () {
var Obj = Json[0];
var KeyNames = Object.keys(Obj)
for (let i = 0; i < KeyNames.length; i++) {
var Head = $(`<th>${KeyNames[i]}</th>`);
$("#FieldNames").append(Head);
}
for (let j = 0; j < Json.length; j++) {
var firstVal = Json[j].name
var secondVal = Json[j].age
var thirdVal = Json[j].email
var fourthVal = Json[j].address
var Data = `
<tr class="middle">
<td>${firstVal}</td>
<td>${secondVal}</td>
<td>${thirdVal}</td>
<td>${fourthVal}</td>
</tr>
`;
$("#Values").append(Data);
}
$('#table_id').DataTable();
});
even though the result is good, it is not what i asked to do.
im trying to figure out ways to make it run automatically but it's not working so well for me..
Alright, I did it a while ago, here's the solution:
I separated my logic into two sections:
1) Create headers:
Loop through the children Objects (as in the Objects in the array) and then get their keys with Object.keys()
The keys are your headers. Then throw them in a row inside thead and voila, your headers
2) Create the fields. This is a bit more complicated.
Loop through the main objects and that will give you the objects one by one as the loop unfolds. Then, create a row for each index. Get the values of each object, and make sure you throw them in the correct row as a td by doing something like I did id='object-" + childIndex + "'. Then grab that specific row, and after you get Object.values() from your object, throw them one by one with a loop inside of the row. TA DA
P.S. Don't ask me why I used jquery. I used it because I'm not a masochist to do this with pure JS
const json = [{
"name": "john",
"age": 35,
"email": "AF#asdsa.com",
"address": "Rishon LeZion"
},
{
"name": "hezi",
"age": 31,
"email": "wertwree#grf.com",
"address": "Rishon LeZion"
},
{
"name": "david",
"age": 23,
"email": "wertewrt#fd.com",
"address": "Rishon LeZion"
},
{
"name": "jacky",
"age": 41,
"email": "wertr#aa.com",
"address": "Rishon LeZion"
}
];
//get headers and create them
const table = $("table");
const thead = $("thead");
var promiseMe = new Promise(function(resolve, reject) {
//to create the headers first based on the objects
var createHeaders = json.forEach((childObjects, index) => {
const kNames = Object.keys(childObjects);
for (let [index, name] of kNames.entries()) {
const actualName = name.replace(/\s+/g, '')
let divId = name.replace(/\s+/g, '-');
let element = document.getElementById(divId);
if (!element) {
thead.append("<td class='header-name' id='" + divId + "'>" + name + "</td>")
}
}
resolve(createHeaders);
})
}).then(createFields());
function createFields() {
const keyNames = Object.values(json);
keyNames.forEach((childObject, childIndex) => {
//create a row for each object
const valArray = Object.values(childObject);
$("#Values").append("<tr id='object-" + childIndex + "' class='rows table-row'></tr>")
valArray.forEach((value, index) => {
$("#object-" + childIndex).append("<td class='cell'>" + value + "</td>")
})
})
}
.cell, .header-name {
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table_id" class="display">
<thead>
</thead>
<tbody id="Values">
</tbody>
</table>

How to apply a key/value to a link using a separate key/value in the same object array

Based on the value key1:V3
I need to store the value keyA:VB into a var then into the link1 anchor.
I need to store the value keyA:VD into a var then into the link2 anchor.
I have been working on this for a while and i cant figure it out. Please help.
var foo = [
{"key1": "V1", "keyA": "VA"},
{"key1": "V2", "keyA": "VB"},
{"key1": "V3", "keyA": "VC"},
{"key1": "V4", "keyA": "VD"},
{"key1": "V5", "keyA": "VE"}
];
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="link1" href="#"></a>
<a id="link2" href="#"></a>
I need the outcome html code to be:
<a id="link1" href="#">VB</a>
<a id="link2" href="#">VD</a>
Thank you in advance
ALTERNATIVE EXAMPLE
var toc = [
{"pageNum": "1", "fileName": "index.html"},
{"pageNum": "2", "fileName": "about.html"},
{"pageNum": "3", "fileName": "work.html"},
{"pageNum": "4", "fileName": "blog.html"},
{"pageNum": "5", "fileName": "contact.html"}
];
var myValue = "V3";
for ( var index = 0; index < foo.length; index++ ){
if ( foo[index].key1 === myValue ){
document.getElementById( "link1" ).innerHTML = foo[index].keyA;
}
}
After long while i have figured out my issue:
toc.filter(function (toc) {
prevPageNum = toc.pageNum - 1;
for (var i = 0; i < Object.keys(toc).length; i++) {
if (prevPageNum === i) {
prevPage = toc.fileName;
$('#prevPage').attr("href",prevPage);
} else {
return
}
}
});
I would truly appreciate if you would remove the "Unclear, Didn't do research" on the main questions. i have been working on this for days. Thank you.

Find element by data attributes that use "|" as separators

Fiddle Example
HTML markup:
<div data-id='23|24|25'></div>
<div data-id='29|30|31'></div>
Script:
var array = [
{
"mid": "24"
},
{
"mid": "26"
},
{
"mid": "28"
},
{
"mid": "29"
},
{
"mid": "30"
},
{
"mid": "31"
}
];
var item_html ="";
$.each(array,function(i,k) {
item_html = '<h3>'+k["mid"]+'</h3>';
$('div[data-id="'+k["mid"]+'"').append(item_html); ???????????
});
Would it be possible to find the div element if part of the "|" separated value in its data-id matches the mid?
I'm trying to get an output like this:
<div data-id='23|24|25'>
<h3>24</h3>
</div>
<div data-id='29|30|31'>
<h3>29</h3>
<h3>30</h3>
<h3>31</h3>
You should use the *= selector (contains):
$('div[data-id*="'+k["mid"]+'"').append(item_html);
The result you are looking for is something tricky. I have update your code. hope this will help you.
var array = [
{ "mid": "24"},
{"mid": "26"},
{"mid": "28"},
{"mid": "29"},
{"mid": "30"},
{"mid": "31"}
];
$('[data-id]').each(function(){
var $this = $(this), dataArr = $this.data('id').split('|'), i = 0;
for(;i< dataArr.length; i++) {
if(numInObjArr(array,dataArr[i])) {
$this.append('<h3>'+ dataArr[i] +'</h3>');
}
}
});
//function to check number in array object provided above
function numInObjArr(objArr, num){
for (var i = 0, len=objArr.length; i< len; i++){
if(objArr[i]["mid"] == num) {
return true;
}
}
return false;
}
http://jsfiddle.net/EZ56N/73/ to see the working example

Categories

Resources