This question already has answers here:
How can I access object properties containing special characters?
(2 answers)
Closed 5 years ago.
I'm working with JSON to query the API provided by themoviedb.org.
I want to make a list of episodes. To do so I need to access the length property of several objects named "season/1", "season/2", "season/3" etc., but I get errors all the time.
The returned JSON Code looks as follows:
"season/1": {
"_id": "5256c89f19c2956ff6046d47",
"air_date": "2011-04-17",
"episodes": [
{
"air_date": "2011-04-17",
"crew": [],
"episode_number": 1,
"guest_stars": [],
"name": "Der Winter naht",
"overview": "Ein Deserteur der Nachtwache bringt erschreckende Nachrichten von den Ländern nördlich der Mauer, und Lord Eddard \"Ned\" Stark soll die Hand des Königs Robert Baratheon werden.",
"id": 63056,
"production_code": "101",
"season_number": 1,
"still_path": "/wrGWeW4WKxnaeA8sxJb2T9O6ryo.jpg",
"vote_average": 7.493,
"vote_count": 67
},
{...},
.
.
.
]
}
My Javascript code:
var urlBase = 'https://api.themoviedb.org/3/tv/';
var tvId = 'XXX';
var apiKey = '?api_key=MYKEY';
var apiLang = '&language=de_DE';
var descElement = document.getElementById('description');
var titleElement = document.getElementById('title');
var posterElement = document.getElementById('poster');
var castElement = document.getElementById('cast');
var seasonsElement = document.getElementById('seasons');
var episodesElement = document.getElementById('episodes');
var votesElement = document.getElementById('votes');
var epGuideElement = document.getElementById('epGuide');
var showRequest = new XMLHttpRequest();
var showUrl = urlBase + tvId + apiKey + apiLang + '&append_to_response=credits';
showRequest.open('GET', showUrl);
showRequest.send();
showRequest.onload = function() {
var data = JSON.parse(showRequest.responseText);
var title = data.name;
var description = data.overview;
var episodes = data.number_of_episodes;
var seasons = data.number_of_seasons;
var votes = data.vote_average;
var cast = '';
for (i = 0; i < data.credits.cast.length; i++) {
cast +=
'<div style="background-color:#dedede;text-align:center;width:145px;height:215px;margin:10px;padding:10px;display:inline-block;float:left;position:relative;"><img src="http://image.tmdb.org/t/p/w90/'
+ data.credits.cast[i].profile_path
+ '" alt="'
+ data.credits.cast[i].name
+ '" style="margin-top:5px;"><br><div style="width:160px;bottom:20px;left:50%;transform:translate(-50%);position:absolute;"><span style="font-size:14px;">'
+ data.credits.cast[i].character
+ '</span><br><strong>'
+ data.credits.cast[i].name
+ '</strong></div></div>';
}
var epGuide = '';
for (i = 1; i <= seasons; i++) {
epGuide += '<h3>Staffel ' + i + '</h3>';
for (ii = 1; ii < data['season/'+i].episodes.length; ii++) {
epGuide += '<p>Folge ' + (ii + 1) + '</p>';
}
}
titleElement.insertAdjacentHTML('beforeend', title);
descElement.insertAdjacentHTML('beforeend', description);
posterElement.src = 'http://image.tmdb.org/t/p/w92' + data.poster_path;
castElement.insertAdjacentHTML('beforeend', cast);
episodesElement.insertAdjacentHTML('beforeend', episodes);
seasonsElement.insertAdjacentHTML('beforeend', seasons);
votesElement.insertAdjacentHTML('beforeend', votes);
epGuideElement.insertAdjacentHTML('beforeend', epGuide);
};
How can I select the "season/i" object with the slash and a variable inside its name?
//EDIT:
There you go, the whole code. Hope, we can find a solution.
In the javascript every variable is a hashTable data-structure and you can access/change its items like an array/hashTable for example:
var person = {name:'Siamand',family:'Maroufi'};
we can access the name property of person object by :
var name= person.name;
or
var name =person['name']
so in your case you can change you code into follwoing:
var epGuide = '';
for (i = 1; i <= seasons; i++) {
epGuide += '<h3>Staffel ' + i + '</h3>';
for (ii = 1; ii < data['season/'+i].episodes.length; ii++) {
epGuide += '<p>Folge ' + (ii + 1) + '</p>';
}
}
example snippet:
var response = `
{
"season/1": {
"_id": "5256c89f19c2956ff6046d47",
"episodes": [{
"air_date": "2011-04-17"
}]
}
}
`;
var data = JSON.parse(response);
var seasons = 2;
var epGuide ="";
for(var i=1;i<seasons;i++){
epGuide += '<h3>Staffel ' + i + '</h3>';
for (ii = 0; ii < data['season/'+i].episodes.length; ii++) {
epGuide += '<p>Folge ' + (ii + 1) + '</p>';
}
}
console.log(epGuide);
by the way the api that you are use hasent such result you said before , it something like follwoing, it has a simple array for seasons
Related
I'm really new to Javascript and pretty much copied most of the code and modified it a bit. Sometimes I'm getting an error putted into a cell and sometimes the correct values. Do you know what is the issue?
for (p=3; p < 19; p=p+3){
var Value = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange(9,p);
var outputValue = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange(counter.getValue(),(3 + a));
outputValue.setValue(Value.getValue());
a = a +1;}
I'm adding the whole code as well for reference:
function getData() {
var queryString = Math.random();
var i;
for (i=2; i < 8; i++) {
var AddressColumn = SpreadsheetApp.getActiveSheet().getRange("W1").getColumn();
//if (ValueCrypto>0)
var cellFunction1 = '=Value(Replace(IMPORTXML("' + SpreadsheetApp.getActiveSheet().getRange(i,AddressColumn).getValue() + '?' + queryString + '","'+ SpreadsheetApp.getActiveSheet().getRange(1,AddressColumn).getValue() + '"),1,1,))*X1';
SpreadsheetApp.getActiveSheet().getRange(i,3).clearContent(); // You can also use range.setFormula("");
SpreadsheetApp.flush();
SpreadsheetApp.getActiveSheet().getRange(i,3).setValue(cellFunction1);
var cellFunction2 = '=Value(Replace(IMPORTXML("' + SpreadsheetApp.getActiveSheet().getRange(i,AddressColumn).getValue() + '?' + queryString + '","'+ SpreadsheetApp.getActiveSheet().getRange(1,AddressColumn).getValue() + '"),1,1,))';
SpreadsheetApp.getActiveSheet().getRange(i,8).clearContent(); // You can also use range.setFormula("");
SpreadsheetApp.flush();
SpreadsheetApp.getActiveSheet().getRange(i,8).setValue(cellFunction2);
}
//var cellFunction2 = '=IMPORTXML("' + SpreadsheetApp.getActiveSheet().getRange('A4').getValue() + '?' + queryString + '","'+ SpreadsheetApp.getActiveSheet().getRange('A5').getValue() + '")';
//SpreadsheetApp.getActiveSheet().getRange('C2').setValue(cellFunction2);
counter2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange("A12").getValue();
SpreadsheetApp.getActiveSheet().getRange("A12").setValue(counter2+1)
if (counter2 = 3) {recordValue();}
}
function recordValue() {
SpreadsheetApp.getActiveSheet().getRange("A12").setValue(0);
var counter = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange("A13");
//console.log(counter)
var dateCell = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange(counter.getValue(),2);
dateCell.setValue(new Date());
//const errorValues = ["#N/A", "#REF", "#ERROR!"];
var a = 0;
for (p=3; p < 19; p=p+3){
var Value = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange(9,p);
var outputValue = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange(counter.getValue(),(3 + a));
outputValue.setValue(Value.getValue());
a = a +1;
}
var TotalValue = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange("R2");
var outputTotalValue = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange(counter.getValue(),17);
outputTotalValue.setValue(TotalValue.getValue());
var TotalValue2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange("R5");
var outputTotalValue2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange(counter.getValue(),18);
outputTotalValue2.setValue(TotalValue2.getValue());
counter.setValue(counter.getValue() + 1);
if(counter.getValue() > 300){counter.setValue("14");}}
I recently started learning html/javascript and I want a temporary object to be filled with one of the objects from an array based on the current page number.
loadnextpage();
function loadnextpage() {
var curpage = allcontent[pagenumber];
pagenumber++;
changeDiv('title', '<span>' + curpage.pageNumber + '</span>' + curpage.title);
}
But when I try to run the code it keeps giving me an error message that curpage is undefined, after that it keeps running and thus the last line of code gives an error, when I ask for curpage.pageNumber. After that it stops running the code.
image clipping of my code with error message
What am I doing wrong?
edit:
here is the entire code:
var pagenumber = 0;
var receipt = [];
var price = 0;
var text = '{"page": [{"pageNumber": "1","title": "kies je formaat","optionName": "size","option": [{"text": "klein","value": "small","extraPrice": "100"},{"text": "middel","value": "medium","extraPrice": "200"},{"text": "groot","value": "large","extraPrice": "300"}]},{"pageNumber": "2","title": "kies je kleur","optionName": "colour","option": [{"text": "rood","value": "red","extraPrice": "10"},{"text": "groen","value": "green","extraPrice": "20"},{"text": "blauw","value": "blue","extraPrice": "30"}]}]}';
var allcontent = [];
allcontent = JSON.parse(text);
var imgpath = 'img/';
loadnextpage();
function loadnextpage(){
var curpage = allcontent[pagenumber];
pagenumber++;
changeDiv('title', '<span>' + curpage.pageNumber + '</span>' +
curpage.title);
var radiobuttons = '';
var radiobuttonid = [];
for(var i = 0; i < curpage.option.length; i++) {
var curradio = curpage.option[i];
radiobuttons += '<label><div class="selection-wrap">';
radiobuttons += curradio.text;
radiobuttons += ' <input type="radio" name="';
radiobuttons += curpage.optoinName;
radiobuttons += '" value="';
radiobuttons += curradio.value;
radiobuttons += '" id="';
radiobuttons += curpage.optoinName;
radiobuttons += '_';
radiobuttons += curradio.value;
radiobuttons += '"></div></label></br>';
radiobuttonid.push(curpage.optoinName + '_' + curradio.value)
}
changeDiv('choices', radiobuttons);
for(var i = 0; i < radiobuttonid.length; i++){
document.getElementById(radiobuttonid[i]).onclick = function(){
receipt[pagenumber-1] = curpage.option[i];
for(var i = 0; i < receipt.length; i++){
price += receipt[i].extraPrice;
}
changeImg('previewimg', imgpath + curpage.option[i].value +
'/preview.jpg');
changeDiv('previewprice', '<h1>€' + price + ',-</h1>');
};
}
};
function changeDiv(id, content) {
document.getElementById(id).innerHTML = content;
};
function changeImg(id, img){
document.getElementById(id).src = img;
};
I'm trying to build a simple site that will check and print out "Buy It Now Prices" for cars. I can't get the JavaScript push function to print out anything but strings.
The eBay API says that buyItNowPrice returns an Amount.
I have experimented with the other Item functions, and the only ones that are working for me are ones that return a String.
The question is, how should the line var itemPrice = item.buyItNowPrice; be formatted to output a number?
function _cb_findItemsByKeywords(root) {
var items = root.findItemsByKeywordsResponse[0].searchResult[0].item || [];
var html = [];
html.push('<table width="100%" border="0" cellspacing="0" cellpadding="3"><tbody>');
for (var i = 0; i < items.length; ++i) {
var item = items[i];
var title = item.title;
var pic = item.galleryURL;
var viewitem = item.viewItemURL;
var itemPrice = item.buyItNowPrice;
var timeLeft = item.watchCount;
if (title != null && null != viewitem) {
html.push('<tr><td>' + '<img src="' + pic + '" border="1">' + '</td>' +
'<td><a href="' + viewitem + '" target="_blank">' +
title + '</a>' // end hyperlink
+
'<br>Item Price: ' + itemPrice +
'<br>Time Remaining: ' + timeLeft +
'</td></tr>');
}
}
html.push('</tbody></table>');
document.getElementById("results").innerHTML = html.join("");
}
// Create a JavaScript array of the item filters you want to use in your request
var filterarray = [{
"name": "MaxPrice",
"value": "250000",
"paramName": "Currency",
"paramValue": "USD"
},
{
"name": "MinPrice",
"value": "15000",
"paramName": "Currency",
"paramValue": "USD"
},
//{"name":"FreeShippingOnly", "value":"false", "paramName":"", "paramValue":""},
{
"name": "ListingType",
"value": ["AuctionWithBIN", "FixedPrice", /*"StoreInventory"*/ ],
"paramName": "",
"paramValue": ""
},
];
// Generates an indexed URL snippet from the array of item filters
var urlfilter = "";
function buildURLArray() {
for (var i = 0; i < filterarray.length; i++) {
var itemfilter = filterarray[i];
for (var index in itemfilter) {
// Check to see if the paramter has a value (some don't)
if (itemfilter[index] !== "") {
if (itemfilter[index] instanceof Array) {
for (var r = 0; r < itemfilter[index].length; r++) {
var value = itemfilter[index][r];
urlfilter += "&itemFilter\(" + i + "\)." + index + "\(" + r + "\)=" + value;
}
} else {
urlfilter += "&itemFilter\(" + i + "\)." + index + "=" + itemfilter[index];
}
}
}
}
}
buildURLArray(filterarray);
// Construct the request
var url = "http://svcs.ebay.com/services/search/FindingService/v1";
url += "?OPERATION-NAME=findItemsByKeywords";
url += "&SERVICE-VERSION=1.0.0";
url += "&SECURITY-APPNAME=REDACTED";
url += "&GLOBAL-ID=EBAY-MOTOR";
url += "&RESPONSE-DATA-FORMAT=JSON";
url += "&callback=_cb_findItemsByKeywords";
url += "&REST-PAYLOAD";
//url += "&categoryId=6001";
url += "&keywords=Ferrari 575";
url += "&paginationInput.entriesPerPage=12";
url += urlfilter;
// Submit the request
s = document.createElement('script'); // create script element
s.src = url;
document.body.appendChild(s);
You are reading the wrong eBay documentation. FindItemsByKeywords is part of the Finding API service. The buyItNowPrice field is found in the item.listingInfo field. Changing the code to the following will output the price.
var itemPrice = '---';
// buyItNowPrice may not be returned for all results.
if(item.listingInfo[0].buyItNowPrice) {
itemPrice = item.listingInfo[0].buyItNowPrice[0]['#currencyId'] + ' ' + item.listingInfo[0].buyItNowPrice[0].__value__;
} else if(item.sellingStatus[0].currentPrice) {
itemPrice = item.sellingStatus[0].currentPrice[0]['#currencyId'] + ' ' + item.sellingStatus[0].currentPrice[0].__value__;
}
I'm trying to get and sort all the items in localStorage and output it to an HTML page.
This is what I'm doing:
<script>
function ShoppingCart() {
var totalPrice = 0;
var output;
var productName;
var productAlbum;
var productQuantity;
var productPrice;
var productSubTotal = 0;
var totalPrice;
for (var i = 0; i < localStorage.length-1; i++){
var keyName = localStorage.key(i);
if(keyName.indexOf('Product_')==0) // check if key startwith 'Product_'
{
var product = localStorage.getItem('Product_'+i);
var result = JSON.parse(product);
var productName;
var productAlbum;
var productQuantity;
var productPrice;
var productSubTotal = 0;
var totalPrice;
productName = result.name
productAlbum = result.album;
productQuantity = result.quantity;
productPrice = parseFloat(result.price).toFixed(2);
productSubTotal = parseFloat(productQuantity * productPrice).toFixed(2);
outputName = "<div id='cart-table'><table><tr><td><b>NAME: </b>" + productName + "</td></tr></div>" ;
outputAlbum = "<tr><td><b>ALBUM: </b>" + productAlbum + "</td></tr>" ;
outputQuantity = "<tr><td><b>QUANTITY: </b>" + productQuantity + "</td></tr>";
outputPrice = "<tr><td><b>PRICE: </b> EUR " + productPrice + "</td></tr>";
outputSubTotal = "<tr><td><b>SUB-TOTAL: </b> EUR " + productSubTotal + "</td></tr></table><br><br>";
var outputTotal = "<table><tr><td><b>TOTAL:</b> EUR " + totalPrice + "</td></tr></table>";
var TotalOutput = outputName + outputAlbum + outputQuantity + outputPrice + outputSubTotal + outputTotal;
document.getElementById("Cart-Contents").innerHTML=TotalOutput;
}
}
alert(TotalOutput);
}
window.onload = ShoppingCart;
</script>
The only item that is being output is the item named 'Proudct_0' in localStorage. Others are not being displayed!
This is what I have in localStorage: http://i.imgur.com/sHxXLOL.png
Any idea why this is happening ?
something wrong in your code.
What do you think if Product_0 not in the localStorage?
var product = localStorage.getItem('Product_'+i);
var result = JSON.parse(product);
may be null and throw an error.
Try this:
for (var i = 0; i < localStorage.length-1; i++){
var keyName = localStorage.key(i);
if(keyName.indexOf('Product_')==0) // check if key startwith 'Product_'
{
var product = localStorage.getItem(keyName);
//do your code here
}
}
Update
document.getElementById("Cart-Contents").innerHTML=TotalOutput;
it's replace, not append
Hope this help!
I am having an issue with this darn array. It was to post my info looking like this. Any ideas how to fix this?
prdpr=10.95^TBCC9^2^Shoes
prdsku=2.50^TDxa2^1^Pants
prdqn=7.50^Tasds^1^Hats
prdcatid=undefined^undefined^undefined^undefined
What it should look like is:
prdpr=10.95^2.50^7.50
prdsku=TBCC9^TDxa2^Tasds
prdqn=2^1^1
prdcatid=Shoes^Pants^Hats
Later I'll just string together for a URL
var advid = "xxx";
var oid = "xxx";
var amt = "20.95";
// This array I cannot mess with, this is just an example
var OrderDetails = new Array();
OrderDetails[0] = ['10.95','2.50','7.50'];
OrderDetails[1] = ['TBCC9','TDxa2','Tasds'];
OrderDetails[2] = ['2','1','1'];
OrderDetails[3] = ['Shoes','Pants','Hats'];
var prdpr = '';
var prdsku = '';
var prdqn = '';
var prdcatid = '';
for(var x = 0; x < OrderDetails.length; x++) {
var delim = "";
if(x == 0){
delim = "";
} else{
delim = "^";
}
prdsku += delim + OrderDetails[x][0];
prdpr += delim + OrderDetails[x][1];
prdqn += delim + OrderDetails[x][2];
prdcatid += delim + OrderDetails[x][3];
}
var output = '<div>Product Sku=' + prdsku + 'Item Cost=' + prdpr + 'Quanty=' + prdqn + 'Category=' + prdcatid + '</div>';
document.write(output);
var OrderDetails = new Array();
OrderDetails[0] = ['10.95','2.50','7.50'];
OrderDetails[1] = ['TBCC9','TDxa2','Tasds'];
OrderDetails[2] = ['2','1','1'];
OrderDetails[3] = ['Shoes','Pants','Hats'];
var delim = '^';
var prdpr = OrderDetails[0].join(delim);
var prdsku = OrderDetails[1].join(delim);
var prdqn = OrderDetails[2].join(delim);
var prdcatid = OrderDetails[3].join(delim);