Im trying to use some JSON data with javascript - javascript

function setup() {
loadJSON("https://api.pandascore.co/lol/champions.json?token=<token>", gotData);
}
function gotData(data) {
var x = data.i.teams.name
for (var i = 0; i < data.length; i++) {
if (x == "Neon Esports") {
document.write(data.i.name);
}
document.write(data.i.teams.name);
}
}
but i am just getting this error Cannot read property 'teams' of undefined

Try this:
function gotData(data) {
data = JSON.parse(data); // let JS know you're dealing with JSON
for (var i = 0; i < data.length; i++) {
var x = data[i].teams[0].name; // we get the name while fetching the data
if (x == "Neon Esports") {
document.write(x);
}
document.write(data[i].teams[0].name);
}
}
Hope I pushed you further.

Related

this.xmlDoc.getElementsByClassName is not a function

Hi im trying to get the score elements from an xmlto then upload to the local storage i have the xml upload as you can see in this image
xmluploaded but when i try to get the elements of Score it appears this error this.xmlDoc.getElementsByClassName is not a function ,i would appreciate the help.
class XML_Database {
constructor () {
this.xmlDoc = null;
}
loadXMLfile(path, callback){
let request = new XMLHttpRequest();
request.open("GET",path,true);
request.setRequestHeader("Content-Type","text/xml");
request.onreadystatechange= function(){
if(request.readyState=== XMLHttpRequest.DONE && request.status==200){
callback(request.responseXML);
}
};
request.send()
}
SearchXML (query, num_scores) {
let Scores = [];
let x = this.xmlDoc.getElementsByClassName(query);
if (num_scores> x.length) {
num_scores= x.length;
}
for (let i = 0; i < num_scores; i++) {
for (let j = 0; j < x[i].childNodes.length; j++) {
if (x[i].childNodes[j].nodeName == "Value") {
Scores.push(x[i].childNodes[j].textContent);
break;
}
}
}
return Scores;
}
setXMLDoc(xmlDoc){
this.xmlDoc = xmlDoc;
}
and this is when i call the methods
set_xml(){
const self = this;
let new_XML_file = "/xml/Scores_Database.xml";
this.XML_db.setXMLDoc(new_XML_file);
this.XML_db.loadXMLfile(new_XML_file,function(xml){
console.log(xml);
self.XML_db.SearchXML("Score", 5) ;
});
}

Problem with showing the results in my Calculator app with this.id

im having trouble using this.id as it doesnt return any value.
https://jsfiddle.net/o432v0L5/
I'm at the point where I want the number to be shown when I press it but it just doesnt work.
for (var i = 0; i < operator.length; i++) {
operator[i].addEventListener('click', function (e) {
alert(this.id)
})
}
var number = document.getElementsByClassName('number')
for (var i = 0; i < number.length; i++) {
number[i].addEventListener('click', function () {
var output = getOutput()
if (output != NaN) {
output = output + this.id;
printOutput(output)
}
})
}```
Have you tried
for (var i = 0; i < operator.length; i++) {
operator[i].addEventListener('click', function (e) {
alert(this.innerText);
})
}

JavaScript Json row undefined for TreeView

I have a question. When querying my Json object, although i have my Field as same name and all Json rows available give me an error that is undefined.
//e.g: row.DepParentId
Bellow is my code. Am I missing some tag?
function convert(rows) {
debugger;
function exists(rows, parent) {
for (var i = 0; i < rows.length; i++) {
if (rows[i].DepId === parent) return true;
}
return false;
}
var nodes = [];
// get the top level nodes
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
if (!exists(rows, row.DepParentId)) {
nodes.push({
id: row.DepId,
name: row.Title
});
}
}
var toDo = [];
for (var i = 0; i < nodes.length; i++) {
toDo.push(nodes[i]);
}
while (toDo.length) {
var node = toDo.shift();
// the parent node
// get the children nodes
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
if (row.DepParentId == node.Id) {
var child = {
Id: row.DepId,
Name: row.Title
};
if (node.options) {
node.options.push(child);
} else {
node.options = [child];
}
toDo.push(child);
}
}
}
return nodes;
}
My Json example for one row picked from Firefox
"{"DepId":7,"DepParentId":3,"Title":"OTT"}"
Thanks for helping
Joao
thanks all for helping, it's working now, the problem was the JSON.stringify() was returning only an [Object] so when you use JSON.parse() generates a sintax error.
function onLoaded() {
var itemsCount = items.get_count();
for (var i = 0; i < itemsCount; i++) {
var item = items.itemAt(i);
var dep = JSON.stringify(item.get_fieldValues());
deps.push(dep);
}
So, i had to change the format to be valid to parse like this
var dt = "[" + deps + "]";
var ret = JSON.parse(dt);
Thanks
Joao

trying to create an array of arrays for return JSON

Im currently working on this script that is written in javascript that returns data from the netsuite ERP platform.
Right now we have the code returning in an array, whilst this is good, it is a result of a dataset of product information.
The script is querying for 3 products, and as a result it returns an array of 21 keys.
this should be returning 3 arrays of arrays so we can handle the content easily externally to Netsuite.
I for the life of me cant figure out which loop I am required to create a new array to manage the content.
function loadRecord(request, response)
{
var recType = request.getParameter('recType');
var savedSearchId = request.getParameter('savedSearchId');
var internalid = request.getParameter('internalid');
//perform the required search.
var filter = [];
if(recType == 'customer' || recType == 'contact' )
{
filter[0] = new nlobjSearchFilter('internalid', null, 'is', internalid); // just get the 1 item by the internal id of the record
}
if( recType == 'item')
{
var internal_ids = new Array();
internal_ids[0] = 25880;
internal_ids[1] = 25980;
internal_ids[2] = 333 ;
filter[0] = new nlobjSearchFilter('internalid', null, 'anyOf', internal_ids); // just get the 1 item by the internal id of the record
}
if(recType == 'transaction')
{
filter[0] = new nlobjSearchFilter('type',null,'anyOf','SalesOrd');
filter[1] = new nlobjSearchFilter('internalid','customer','is', internalid );
}
var rsResults = nlapiSearchRecord(recType, savedSearchId, filter);
var rsObj = [];
// not sure how to make each row a new array of arrays so it is structured more elegantly...
for (x = 0; x < rsResults.length; x++)
{
var flds = rsResults[x].getAllColumns();
for (i = 0; i < flds.length; i++)
{
var rowObj = {};
rowObj.name = flds[i].getName();
rowObj.label = flds[i].getLabel();
rowObj.val = rsResults[x].getValue(flds[i].getName(), flds[i].getJoin(), flds[i].getSummary());
rowObj.txtval = rsResults[x].getText(flds[i].getName(), flds[i].getJoin(), flds[i].getSummary())
rsObj.push(rowObj);
}
}
response.write(JSON.stringify(rsObj));
}
Any help greatly appreciated
Is this what you're looking for?
var rsObj = [];
var rowArr, fields, x, i;
for (x = 0; x < rsResults.length; x++)
{
flds = rsResults[x].getAllColumns();
for (i = 0; i < flds.length; i++)
{
rowArr = rsObj[x] = [];
rowArr.push(flds[i].getName());
rowArr.push(flds[i].getLabel());
rowArr.push(rsResults[x].getValue(flds[i].getName(), flds[i].getJoin(), flds[i].getSummary()));
rowArr.push(rsResults[x].getText(flds[i].getName(), flds[i].getJoin(), flds[i].getSummary()));
}
}
console.log(rsObj[0][0]); // row0.name
console.log(rsObj[2][1]); // row2.label
Maybe something like this:
for (var x = 0; x < rsResults.length; x++)
{
var flds = rsResults[x].getAllColumns();
for (var i = 0; i < flds.length; i++)
{
rsObj.push({
name: flds[i].getName(),
label: flds[i].getLabel(),
val: rsResults[x].getValue(flds[i].getName(), flds[i].getJoin(), flds[i].getSummary()),
txtval: rsResults[x].getText(flds[i].getName(), flds[i].getJoin(), flds[i].getSummary())
});
}
}
If you are using ECMAScript5, you cold simplify the loop with forEach, like this:
rsResults.forEach(function(result) {
result.getAllColumns().forEach(function(fields) {
rsObj.push({
name: fields.getName(),
label: fields.getLabel(),
val: result.getValue(fields.getName(), fields.getJoin(), fields.getSummary()),
txtval: result.getText(fields.getName(), fields.getJoin(), fields.getSummary())
});
});
});
This must solve you problem. Some declaration problem might be there.
var rsObj = [];
for (int x = 0; x < rsResults.length; x++)
{
var flds = rsResults[x].getAllColumns();
for (int i = 0; i < flds.length; i++)
{
var rowObj = [];
rowObj.push(flds[i].getName());
rowObj.push(flds[i].getLabel());
rowObj.push(rsResults[x].getValue(flds[i].getName(), flds[i].getJoin(), flds[i].getSummary()));
rowObj.push(rsResults[x].getText(flds[i].getName(), flds[i].getJoin(), flds[i].getSummary()));
rsObj.push(rowObj);
}
}

returning a value after for loops

So, I have been trying for the past few hours to get an result out of a function after performing some for loops :
Cluster.prototype.initiate_api_data_fetching = function(username) {
var self = this,
object = [];
return self.initiate_available_market_search(username, function(data_object){
var json_obj = JSON.parse(data_object);
for(var obj_key in json_obj) {
for (var i = json_obj[obj_key].length - 1; i >= 0; i--) {
self.initiate_market_items_data_fetching(username, json_obj[obj_key][i].site, function(data_obj){
var json_object = JSON.parse(data_obj);
for(var data_key in json_object) {
for (var j = json_object[data_key].length - 1; j >= 0; j--) {
object.push(json_object[data_key][j]);
/*log(object);*/
};
};
log(object);
});
};
};
});
};
Making abstraction of all the variables and other things that make no sense to you readers, I would just like to know how can I return the object array with the data that I\m pushing in it. Everything is fine if I\m logging where the /*log(object);*/ is, but if I want to see what the object contains at the end of the function, I get an empty array.
I suggest you add a callback to your main function and call it when done..
Cluster.prototype.initiate_api_data_fetching = function (username, callback) {
var self = this,
object = [];
return self.initiate_available_market_search(username, function (data_object) {
var json_obj = JSON.parse(data_object)
, counter = 0;
function done() {
counter -= 1;
if (counter === 0) {
callback(object);
}
}
for (var obj_key in json_obj) {
if (!json_obj.hasOwnProperty(obj_key)) { continue; }
for (var i = json_obj[obj_key].length - 1; i >= 0; i--) {
counter += 1;
self.initiate_market_items_data_fetching(username, json_obj[obj_key][i].site, function (data_obj) {
var json_object = JSON.parse(data_obj);
for (var data_key in json_object) {
if (!json_object.hasOwnProperty(data_key)) { continue; }
for (var j = json_object[data_key].length - 1; j >= 0; j--) {
object.push(json_object[data_key][j]);
/*log(object);*/
}
}
done();
});
}
}
});
};
PS. 1 assumption is that initiate_api_data_fetching is async.
PS. 2 Follow the advice from the commenters above to improve your code. I answered your immediate question by showing you how to synchronise async calls, but don't stop there.

Categories

Resources