Match key/values in JSON object - javascript

I have a school project where we are learning JSON. What I am trying to do is figure out how I can match keys with other keys that exist in another object property.
I'm using an old api to pull nfl player information. Here is an example of the url to pull the data:
http://api.fantasy.nfl.com/v1/players/stats?statType=seasonStats&season=2018&week=16&format=json
I'm using AJAX to call the data and stringify the results into a table.
$.ajax({
url: queryURL,
method: "GET"
}).then(function(response) {
var tbl = $("<table>");
$(tbl).addClass("table");
var objCount = JSON.stringify(response.players.length);
$(tbl).append("<thead><tr><th>ID</th><th>Team</th><th>POS</th>
<th>Player</th><th>Stat</th></tr></thead><tbody>");
for (p = 1; p < 2; p++) {
var id = response.players[p].id;
var team = response.players[p].teamAbbr;
var pos = response.players[p].position;
var plyr = response.players[p].name;
var stat = JSON.stringify(response.players[p].stats);
var plyrStatsObjLen =
JSON.stringify(response.players[p].stats.length);
console.log("statObjLength: " + plyrStatsObjLen);
$.each(response.players[p].stats, function(key, value) {
console.log(key + ": " + value);
});
$(tbl).append("<tr><td>" + id + "</td><td>" + team + "</td><td>" + pos + "</td><td>" + plyr + "</td><td>" + stat + "</td>");
}
$(tbl).append("</tbody><br/><br/>");
$("#statOutput").append(tbl);
});
Here is a fiddle of what I am doing:
https://jsfiddle.net/kenneth2k1/kcf5duLr/
If you notice the results, I have the stats property separated out in its own column, but it is still in the object's key/value structure.
Now, here is another url that has what each stat is:
https://api.fantasy.nfl.com/v1/game/stats?format=json
"stats": [
{
"id": 1,
"abbr": "GP",
"name": "Games Played",
"shortName": "GP"
},
{
"id": 2,
"abbr": "Att",
"name": "Passing Attempts",
"shortName": "Pass Att"
},
{
"id": 3,
"abbr": "Comp",
"name": "Passing Completions",
"shortName": "Pass Comp"
}, ... and so on
So for example key ID "1" corresponds with "Games Played" from the stat reference object.
I am new to all this, so what I can't wrap my head around is if I wanted to sub out the keys in my output with the corresponding name value from the stats reference object, how would I do that?
For example from the jsfiddle output, Instead of
{"1":"9","13":"1"}
It would say
Games Played: 9, Rushing Attempts: 1
I hope that makes sense. Basically I'd like to learn how to match keys in one JSON object with the key values in another.
Thank you very much for assistance.

You could nest your second AJAX call in the success function of your first call, then put your variable assignments and table creation into the second success function. Inside the second success function you'd use simple for loops to match each numerical statistic from the player data with the correct name of the statistic in the statistics data, like this:
$(document).ready(function () {
var statType = "seasonStats";
var season = "2018";
var week = "15";
var playersURL = "https://api.fantasy.nfl.com/v1/players/stats?format=json" + "&statType=" + statType + "&season=" + season + "&week=" + week;
var statURL = "https://api.fantasy.nfl.com/v1/game/stats?format=json";
// Now we get the stats
$.ajax({
url: statURL,
method: "GET",
success: function (response) {
const stats = response.stats;
// Then we get the players
$.ajax({
url: playersURL,
method: "GET",
success: function (response) {
const players = response.players;
// Now we do the rest of the logic
// Here's our table creation and header
var tbl = $("<table>");
$(tbl).addClass("table");
$(tbl).append("<thead><tr><th>ID</th><th>Team</th><th>POS</th><th>Player</th><th>Stat</th></tr></thead><tbody>");
// Here's where we create variables for each individual player
for (p = 0; p < 1; p++) {
let id = players[p].id;
let team = players[p].teamAbbr;
let pos = players[p].position;
let plyr = players[p].name;
// We create an empty object to hold the named statistics we're about to find
let statistics = {};
// Now we'll loop over the players and statistics to get names for all the stats
playerStats = players[p].stats;
for (playerStat in playerStats) {
for (s = 0; s < stats.length; s++) {
// if the player's statistic matches the id of the property from the stats object, we add that stat name and its total for that player as a property of the object we created above
if (playerStat === JSON.stringify(stats[s].id)) {
let statName = stats[s].name;
let statCount = playerStats[playerStat];
statistics[statName] = statCount;
}
}
};
// Now we turn our statistics object into text that can actually go into our table
let prettyStats = "";
for (statistic in statistics) {
prettyStats = prettyStats + `${statistic}: ${statistics[statistic]}
`
}
// Now that we have data for the player, we add a row to our table
$(tbl).append("<tr><td>" + id + "</td><td>" + team + "</td><td>" + pos + "</td><td>" + plyr + "</td><td>" + prettyStats + "</td>");
}
//Here's the bottom of our table and its creation inside the div
$(tbl).append("</tbody><br/><br/>");
$("#statOutput").append(tbl);
}
});
}
});
});
You'll probably want to do further text formatting on the output of prettyStats, but it gets you the data you're looking for.

Related

How can i get a certain amount of JSON data from an API?

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

JS: OpenWeatherMap API returns "undefinded" for parameter "rain.3h"

I'd like to have some parameters from this API in my "home.php".
I already got values for parameters cloud, min & max temp, wind etc. ...
But in case of rain.3h my console shows an error, because of the number "3" behind the point. So i put it into brackets and it returns now "undefinded". Do you have any suggestions to solve this problem? (Parameter rain is set for this JSON response because i see the value in the browser-console.
Here´s my code:
function getWeatherData(weatherlat, weatherlong) {
var url = "http://api.openweathermap.org/data/2.5/forecast?lat=" + weatherlat + "&lon=" + weatherlong + "&units=metric&APPID=88e60f2ce52794ed240874b235f21794";
$.ajax({
url: url
}).done(data => {
let nextForecast = data.list[0].main;
let cloudy = data.list[0].clouds;
let weatherCond = data.list[0].weather[0];
let windy = data.list[0].wind;
let rainy = data.list[0].rain;
console.log(data);
$('#progressbar2').addClass('hidden');
//"<img src='http://openweathermap.org/img/w/" + data.weather[0].icon + ".png' alt='Icon depicting current weather.'>"
document.getElementById("weathercond").innerHTML = `${weatherCond.description}`;
document.getElementById("weathericon").innerHTML = "<img src='http://openweathermap.org/img/w/" + weatherCond.icon + ".png' alt='Icon depicting current weather.'>";
document.getElementById("cloud").innerHTML = `${cloudy.all}%`;
document.getElementById("mintemp").innerHTML = `${nextForecast.temp_min}°C`;
document.getElementById("maxtemp").innerHTML = `${nextForecast.temp_max}°C`;
document.getElementById("luftftgk").innerHTML = `${nextForecast.humidity}%`;
document.getElementById("windrtg").innerHTML = `${windy.deg}°`;
document.getElementById("windspeed").innerHTML = `${windy.speed}m/s`;
document.getElementById("rainfall").innerHTML = `${['rainy']['3h']}mm`;
});

How do I use JSON data?

When I query a server I get a JSON file in return. The JSON file I get back would be in the following format.
{
"head": {
"link": [],
"vars": ["bookName", "author"]
},
"results": {
"distinct": false,
"ordered": true,
"bindings": [
{
"bookName": {
"type": "literal",
"xml:lang": "en",
"value": "Of Mice and Men"
},
"author": {
"type": "literal",
"xml:lang": "en",
"value": "John Steinbeck"
}
}
]
}
}
This is what I have done so far:
$.ajax({
dataType: "jsonp",
url: queryUrl,
success: function(data) {
// get the table element
var table = $("#results");
// get the sparql variables from the 'head' of the data.
var headerVars = data.head.vars;
// using the vars, make some table headers and add them to the table;
var trHeaders = getTableHeaders(headerVars);
table.append(trHeaders);
// grab the actual results from the data.
var bindings = data.results.bindings;
var book = data.results.bindings[1].bookName.value;
// for each result, make a table row and add it to the table.
var numberOfBooks = 0;
for(rowIdx in bindings){
table.append(getTableRow(headerVars, bindings[rowIdx]));
numberOfBooks++;
}
document.getElementById("searched-for").innerHTML="<h1>You seach for " + '"' + input + '"' + " and we found " + numberOfBooks + " books </h1>";
}
});
What I want to be able to do is something like this:
var book = data.results.binding[1].bookName.value;
Try this:
$.ajax({
dataType: "jsonp",
url: queryUrl,
success: function(data) {
// get the table element
var table = $("#results");
// get the sparql variables from the 'head' of the data.
var headerVars = data.head.vars;
// using the vars, make some table headers and add them to the table;
var trHeaders = getTableHeaders(headerVars);
table.append(trHeaders);
// grab the actual results from the data.
var bindings = data.results.bindings;
var book;
if(bindings && bindings.length) {
book = bindings[0].bookName.value;
}
// for each result, make a table row and add it to the table.
var numberOfBooks = 0;
for(rowIdx in bindings){
table.append(getTableRow(headerVars, bindings[rowIdx]));
numberOfBooks++;
}
document.getElementById("searched-for").innerHTML="<h1>You seach for " + '"' + input + '"' + " and we found " + numberOfBooks + " books </h1>";
}
});
But that will only get the first book, if it exists.

How to access all nested associative array elements?

Situation : I receive JSON array from jQuery <-> PHP Ajax request. Here's structure of unparsed JSON aray :
{"Focus":{"id":2,"brand":"Ford","name":"Focus"}}
And after using JSON.parse(json); the structure looks like :
Focus: Object
brand: "Ford"
id: 2
name: "Focus"
Problem : I want to access all array's '1st tier' elements and use them like an object, but none of the following ways works :
for (var entity in dataTable)
{
formattedText += entity['brand'] + " " + entity['name'] + "<br>";
OR
formattedText += entity.brand + " " + entity.name + "<br>";
OR
formattedText += dataTable[0]['brand'] + " " + dataTable[0]['name'] + "<br>";
}
Any solutions how to read values of all object in this array?
The for..in loop uses keys and does not return the elements themself: for (var key in dataTable)You would then access each element with dataTable[key]. The key is actually the name of the Element.
You where using it as you would use a for..of loop, but that is a new feature not supported in all Browsers yet.
Demo:
var dataTable = {"Focus":{"id":2,"brand":"Ford","name":"Focus"}}
var formattedText = ""
for (var key in dataTable)
{
formattedText += dataTable[key]['brand'] + " " + dataTable[key]['name'] + "<br>";
}
document.write(formattedText)
Object.keys will return array of all the keys of the object
You can loop(forEach/for-loop) through the keys to get the expected output.
Using forEach:
var dataTable = {
"Focus": {
"id": 2,
"brand": "Ford",
"name": "Focus"
}
}
var keys = Object.keys(dataTable);
var str = '';
keys.forEach(function(item) {
str += dataTable[item].brand + " " + dataTable[item].name;
});
alert(str);
Using for-loop:
var dataTable = {
"Focus": {
"id": 2,
"brand": "Ford",
"name": "Focus"
}
}
var keys = Object.keys(dataTable);
var str = '';
for (var i = 0, len = keys.length; i < len; i++) {
str += dataTable[keys[i]].brand + " " + dataTable[keys[i]].name;
}
alert(str);
The correct syntax to write this would be:
When you loop, you'll get the key name in the variable entity and then use that to get the value, also, you need to access the associative array inside the first key i.e. Focus
var dataTable = JSON.parse('{"Focus":{"id":2,"brand":"Ford","name":"Focus"}}');
var formattedText = '';
for (var entity in dataTable.Focus) {
formattedText += dataTable.Focus['brand'] + " " + dataTable.Focus['name'] + "<br>";
}
Sounds like you're using each function in a wrong way. in your each function change arguments to key and value like this:
$.each(dataTable, function (key, value) {
//access key and values here
});
In your case u should iterate again over key and values of your key values.

How to send table column values from a Javascript page to a C# page using Jquery

I have values that come from a dynamically created table from it's selected rows. inside each selected row i want all the td.innerText values that belong to be sent to a C# page, but i don't know how to. I was using JSON but I dont know if i used it properly.
function selectedRows()
{
var selectedItems = $('#ScannedLabelTable').find(':checkbox:checked').parents('tr');
var serial, kanbanNumber, customer, description, quantity;
$.each(selectedItems, function (i, item) {
var td = $(this).children('td');
for (var i = 0; i < td.length; ++i)
{
serial = td[1].innerText;
kanbanNumber = td[2].innerText;
customer = td[3].innerText;
description = td[4].innerText;
quantity = td[5].innerText;
}
console.log(serial + ' ' + kanbanNumber + ' ' + customer + ' ' + description + ' ' + quantity);
});
$.ajax({
url: SEND_TO_TEXTFILE_PAGE
, data: "labelSerial=" + serial + "&kanbanNumber=" + kanbanNumber + "&customer="
+ customer + "&description=" + description + "&quantity=" + quantity
, dataType: 'json'
, success: function (status) {
if (status.Error) {
alert(status.Error);
}
}
, error: Hesto.Ajax.ErrorHandler
});
}
EDIT: sorry I must have read this too quickly. This should do it. create an array and add the data object to it in the loop.
If you just create a json object using key value pairs you can send that object to your c# controller.
function selectedRows() {
var selectedItems = $('#ScannedLabelTable').find(':checkbox:checked').parents('tr');
var serial, kanbanNumber, customer, description, quantity;
var dataArray = new Array();
$.each(selectedItems, function (i, item) {
var td = $(this).children('td');
for (var i = 0; i < td.length; ++i)
{
var InfoObject = {
serial: td[1].innerText;
kanbanNumber: td[2].innerText;
customer: td[3].innerText;
description: td[4].innerText;
quantity: td[5].innerText;
};
dataArray.push(InfoObject);
}
});
$.ajax({
url: SEND_TO_TEXTFILE_PAGE
, data: dataArray
, dataType: 'json'
, success: function (status) {
if (status.Error) {
alert(status.Error);
}
}
, error: Hesto.Ajax.ErrorHandler
});
}

Categories