How to fetch an array object from json file - javascript

JSON: https://www.cc.puv.fi/~asa/cgi-bin/fetchOrders.py
Im trying to fetch objects and arrays within the object but im only fetching the objects.
How do i fetch also "products" arrays?
My javascript code:
fetch('https://www.cc.puv.fi/~asa/cgi-bin/fetchOrders.py')
.then(res => res.text())
.then(teksti => tulostus(teksti))
function tulostus(txt) {
console.log(txt);
let tilaukset = JSON.parse(txt);
console.log(tilaukset);
let a = "<table><tr><th>orderid</th><th>customerid</th><th>customer</th><th>invaddr</th><th>delivaddr</th><th>deliverydate</th><th>respsalesperson</th><th>comment</th><th>totalprice</th></tr>";
for(let i = 0; i < tilaukset.length; i++) {
let tilaus = tilaukset[i];
console.log(tilaus)
console.log(tilaus.orderid);
a += '<tr><td>' + tilaus.orderid + '</td><td>' + tilaus.customerid + '</td><td>' + tilaus.customer + '</td><td>' + tilaus.invaddr + '</td><td>' + tilaus.delivaddr + '</td><td>' + tilaus.deliverydate + '</td><td>' + tilaus.respsalesperson + '</td><td>' + tilaus.comment + '</td><td>' + tilaus.totalprice + '</td></tr>'
}
console.log(a);
document.getElementById('info').innerHTML = a+'</table>';
}

You likely are fetching the products array but need to add some code to iterate over it.
for(let i = 0; i < tilaukset.length; i++) {
let tilaus = tilaukset[i];
console.log(tilaus)
console.log(tilaus.orderid);
a += '...'
for (let j=0; j < tilaus.products.length; j++) {
console.log(tilaus.products[i].name);
}
}
Replace the console log in the loop with some code to write to the html as you were doing above. Depending on how you'd like it to look at might get tricky, so consider abstracting away HTML generation or using a library that helps you componentize the ui.

fetch("https://www.cc.puv.fi/~asa/cgi-bin/fetchOrders.py").
then(response => response.json())
.then(result => display(result))
let display = (result) => {
for (let i = 0; i < result.length; i++) {
let products = result[i].products
// here products is a Object array
for(let i=0;i<products.length;i++){
let product = products[i];
console.log(product)
// add your stuff here like product.orderid to get orderid
}
}
}

you're already looping over the array and getting the object from there, if you check there's product array there in every array value(tialus.products) just save that value in a variable

Related

how to list all local storage on page properly in javascript?

I am trying to show all my localstorage items value on my index page but for some reason it is not showing. can anyone see what I am doing wrong in my code below. In my index page script I am looping thorough the length of local storage and trying to display them on screen, only thing that display is one item. Please help. thanks for your help.
here is my code (index page script):
document.addEventListener("DOMContentLoaded", function (event) {
var dataFromLocalStorage = "";
for (var i = 0; i < localStorage.length; i++) {
dataFromLocalStorage =
dataFromLocalStorage + " " + localStorage.getItem(`key${i}`);
}
document.querySelector("#content").innerHTML = dataFromLocalStorage; // Updating same thing
})
The other script where I load it to localStorage:
var addToTheContent = document.getElementById("canvas");
var scheduleEvent = document.getElementById("scheduleStartTime");
var candidateId = document.getElementById('candsId');
var getCandId = document.getElementById("candsId");
var displayCandId = candidateId.options[candidateId.selectedIndex].value;
var id = 1;
function addTheEvent() {
var showText = addToTheContent.innerHTML = displayCandId + " ( " + scheduleEvent.value + " ) ";
localStorage.setItem(`key${id}`, JSON.stringify(showText))
id += 1
localStorage.getItem(`key${id}`);
window.location = "/";
}
"key${id}" is a template string, you need to use backticks `` instead of quotation marks "".
You could also loop through localStorage as you normally would for most JavaScript objects:
for(var key in localStorage) {
if(localStorage.hasOwnProperty(key)) { // ignore the prototype methods
// Do whatever you want with key and value found here
console.log(key + ": " + localStorage[key]);
}
}
Typo: Use i instead id
var dataFromLocalStorage = localStorage.getItem(`key${id}`);
correct:
var dataFromLocalStorage = `localStorage.getItem("key${i}");
Another thing, You are updating same innerHTML
var dataFromLocalStorage = "";
for (var i = 0; i < localStorage.length; i++) {
dataFromLocalStorage =
dataFromLocalStorage + " " + localStorage.getItem(`key${i}`);
}
document.querySelector("#content").innerHTML = dataFromLocalStorage; // Updating same thing
// do something with localStorage.getItem(localStorage.key(i));
// missing template string 'key${id}'
var id = 1;
function addTheEvent() {
var showText = displayCandId + " ( " + scheduleEvent.value + " ) ";
localStorage.setItem(`key${id}`, JSON.stringify(showText));
id += 1;
window.location = "/";
}

How do I access children data in JSON response using Javascript/GAS

I am trying to access children data from a Json response to use it in an if statement but i don't know-how. Anyone know how to do this?
Here is the screenshot of the response and I have circled the object I want to access. I want only the summation to happen if the approval has a value i.e. status needs to be pending or approved, otherwise, no calculation will happen.
Here is the code that I use but don't know how to access the approaval={data=[{status}] form the JSON so as to use it
function showTimeData() {
var users = getUsers()
var endpoint = 'users/';
var time_array = [];
for (var i = 0; i < users.length; i++) {
var url = 'https://api.10000ft.com/api/v1/users/' + users[i].id + '/time_entries?fields=approvals' + '&from=' + from + '&to=' + to + '&auth=' + TKF_AUTH;
var response = UrlFetchApp.fetch(url, options);
var info = JSON.parse(response.getContentText());
var content = info.data;
var total_hours = 0;
for (var j = 0; j < content.length; j++) {
if (content.data.approvals.data.length > 0) {
hoursTotal = 0;
}
total_hours += parseInt(content[j].hours);
}
Logger.log('User name: ' + users[i].display_name + ' ' + 'User id: ' + users[i].id + ' ' + 'total hours: ' + total_hours)
}
First of all. You need to fix the error(mentioned in the chat in comments):
Replace this
if (content.data.approvals.data.length > 0) {
hoursTotal = 0;
}
with this
if (content[j].approvals.data.length > 0) {
hoursTotal = 0;
}
Then what you need is:
content[0].approvals.data[0].status
or an array of statuses:
content[0].approvals.data.map(el => el.status)
or an array of all statuses:
content.map(el => el.approvals.data.map(it => it.status)).flat(1)
but last example will work only in fairly new browsers.

Datatables row reorder event issue

var table =$("#exampleList").DataTable({
paging:false,
rowReorder:false
}
});
table.on('row-reorder',function(e, diff,edit){
for(var i=0, ien = diff.length ; i<ien ; i++){
var rowData = table.row(diff[i].node).data();
sequence = sequence + "_" + rowData[0];
}
var data = table.rows().data();
data.each(function (value, index) {
alert('Data in index: ' + index + ' is: ' + value);
});
});
Hi,
I am new to datatables. Issue I am having right now is I cant get the latest value in my table after the user reorder the row. The code above only shows the value before the reorder occurs. I need to get the latest reorder sequence so I can update the database.
What you need to do is wait a few milliseconds before trying to read the data.
table.on('row-reorder',function(e, diff, edit){
for(var i=0, ien = diff.length ; i<ien ; i++){
var rowData = table.row(diff[i].node).data();
sequence = sequence + "_" + rowData[0];
}
setTimeout(()=> { lookAtData() }, 10);
});
function lookAtData() {
var data = table.rows().data();
data.each(function (value, index) {
alert('Data in index: ' + index + ' is: ' + value);
});
}
You should use column-reorder not row-reorder.
Please try :
var rdata = table .columns().order().data();
console.log(rdata);
It will get the data after columns ordering.

What am I doing wrong in this javascript loop operation?

I've called some data from php using AJAX, and the result if I code alert(data.a) looks like this...
({a:[{my_id:"34", name:"Dave"}, {my_id:"39", name:"Barry"}]}
I'm not sure how to loop through this to extract the values.
My latest code...
for (var key in data.a)
{
if (data.a.hasOwnProperty(key))
{
alert(key + " -> " + data.a[key]);
}
}
... displays
0 -> [object Object]
and this displays the same too...
for (var i=0, tot=data.a.length; i < tot; i++)
{
for (var key in data.a[i])
{
if (data.a[i].hasOwnProperty(key))
{
alert(key + " -> " + data.a[i][key]);
}
}
}
What's the trick to looping through these results to extract the data for display?
If it helps, here's what I send at the end of my php...
$x['a'] = $myArray;
echo json_encode($x);
Thanks for your time and help.
Are you after something like this? Loop through all the objects the print out all of their properties and values?
for (var i = 0; i < data.a.length; i++) {
var objectInArray = data.a[i];
var keys = Object.keys(objectInArray);
for (var j = 0; j < keys.length; j++) {
var key = keys[j];
alert(key + " -> " + objectInArray[key]);
}
}
When you are doing data.a[key] in for loop, you are getting a json object: {my_id:"34", name:"Dave"} for key = 0, and {my_id:"39", name:"Barry"} for key = 1. So in order to get values you should do something like this:
for (var key in data.a)
{
if (data.a.hasOwnProperty(key))
{
alert(key + " -> " + data.a[key].my_id);
// data.a[key].name to get name attribute
}
}
Is it just
for (var i=0; i < data.a.length; i++) {
alert(data.a[i].my_id + " -> " + data.a[i].name);
}
In your example, data.a is an array of objects, so this would work:
for (var i = 0; i < data.a.length; i++) {
console.log('my_id: ' + data.a[i].my_id);
console.log('name: ' + data.a[i].name);
}

Listing localstorage

I did my own feature using this:
function save(title, url)
{
for (var i = 1; i < localStorage.length; i++)
{
localStorage["saved-title_" + i + ""] = title;
localStorage["saved-url_" + i + ""] = url;
}
}
function listFavs()
{
for (var i = 1; i < localStorage.length; i++) {
console.log(localStorage["saved-fav-title_" + i + ""]);
}
}
save() happens when someone clicks on this:
onclick="save(\'' + title + '\', \'' + tab.url + '\');"> ' + title + '</a>';
However... it doesn't show the saved localStorages, how am I supposed to make it work?
Might it be because you are using the key 'saved-title_' + i to save the value and 'saved-fav-title_' + i to retrieve it?
The difference is the fav- part.
And your enumeration of the localStorage is bound to create errors as there is no guarantee that all items in it have a key that matches the pattern provided 'saved-fav-title_' + i - actually it is guaranteed to not be so as you are yourself inputting items with keys in the form of 'saved-url_'+ i.
So, if you want to properly enumerate the items with a key matching a pattern use
function listFavs(){
var key;
for (var i = 0, len = localStorage.length; i < len; i++){
key = localStorage.key(i);
if ((/^saved-fav-title_/).test(key)) {
console.log(localStorage.getItem(key);
}
}
}

Categories