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.
Related
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
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 = "/";
}
pretty new programmer here, hopefully, this isn't too much of a rudimentary question, just couldn't find the answer anywhere (maybe I just don't know how to look?).
I'm currently working with the BandsInTown API and everything is working great, aside from the fact that I'm receiving way more objects than I need.
I would just like to know if there is a way that I can specify a certain number of objects that I want to receive back?
Any help is appreciated.
require("dotenv").config();
var keys = require("./keys.js");
var request = require('request')
var moment = require('moment')
var media = process.argv.slice(3).join(" ")
function bandsFunct() {
var artist = "";
for (var i = 3; i < process.argv.length; i++) {
if (i !== 3) artist += "-"
artist += process.argv[i];
}
if (process.argv[2] == "concert-this")
request("https://rest.bandsintown.com/artists/" + artist + "/events?app_id=codingbootcamp", function (error, response, body) {
console.log(response.body)
var body = JSON.parse(body)
console.log(" ")
console.log("-------------------------------------")
console.log(" ")
console.log("Upcoming concerts for " + artist + ": ");
for(var set in body) {
var date = moment(body[set].datetime).format("MM/DD/YYYY")
console.log(body[set].venue.city + ", " + "at " + body[set].venue.name + ", " + "on " + date)
}
console.log(" ")
console.log("-------------------------------------")
console.log(" ")
})
}
bandsFunct();
suppose you have a object
let obj = {
{ name: 'war', class :'12' , age: 21, field: 'cse' } ,
{ name: 'jar', class :'120' , age: 251, field: 'csee' }
}
if you want some selected fields you can do like this
var result = Object.keys(obj).filter(item =>
item.class < 100 // you can specify any condition
)
// the result will contain only those objects whose class < 100
In PHP it's easy to create variables.
for($i=1; $i<=$ges; $i++) {
${"q" . $i} = $_POST["q".i];
${"a" . $i} = $_POST["a".i];
}
The result is $a1 = $_POST["q1];
How is the right way for that in jQuery?
I need to create it dynamicly for an ajax dataset.
for (var i = 1; i < ges; ++i) {
var finalVar = "input[name='a" + i + "']:checked";
var qtext = $("#q"+ i).text();
if ($(finalVar).val() == null) {
qvar = 0
} else {
qvar = $(finalVar).val();
}
//write question text and value in q1, a1, q2, a2,...
//generate ajax data
params = params + "q" + i + ":" + "q" + i + ", " + "a" + i + ":" + "a" + i + ","
}
I want to set the question text in q1 and the answer in a1.
Well if am not wrong you want to accumulate answers related to questions from the HTML and want to send the data through ajax..
So u can do something like this:
var QnA = {};
$('.eventTrigger').click(function(e) {
e.preventDefault();
$('#parent').find('.QnA').each(function() {
QnA[$(this).find('.Que').text()] = $(this).find('.Ans').val();
})
console.log(QnA);
})
https://jsfiddle.net/jt4ow335/1/
The only thing you can do about it, is:
var obj = {}
for(var i = 0; i < 10; i++)
obj['cell'+i] = i
console.log(obj)
and pass obj as data
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);
}
}
}