Question
How can i set up a working example of of these planes.
Background
I have the first part working, so it seems that perhaps my loop is off? I can at least pull the number of planes. But having a problem displaying all the planes.
Here is my Demo on CodePen
I am looking at the documentation from https://developers.wargaming.net/reference/all/wowp/encyclopedia/planes/?application_id=demo&r_realm=eu
but they don't have a fully functioning example. I want to show the name of the plane, country, and show a large image. I can style it later but need a working example to help me understand and get started.
Code
API
I am pulling data from https://api.worldofwarplanes.eu/wowp/encyclopedia/planes/?application_id=demo
JSON output
HTML
<p>There are a total of <span id="planeQuantity"></span> planes in the database.</p>
<ul id="planes"></ul>
jQuery from
https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js
Javascript
var queryURL = "https://api.worldofwarplanes.eu/wowp/encyclopedia/planes/?application_id=demo";
$.getJSON(queryURL, function (data) {
var quantity = data.meta.count;
$('#planeQuantity').append( quantity );
var name = data.id.name_i8n;
var nation = data.id.nation;
var lrgImg = data.id.images.large;
$(data).each(function(){
console.log($(this).id);
$('#planes').append('<li>' + name + 'is from ' + nation + '<img src="' + lrgImg + '">' + '</li>');
});
})
I adjusted your code a bit. Some comments:
your data.data is a Object. so, you can use for (key in object) for each key iteration (you can use jQuery's each too, but this is a pure JS approach);
name_i8n is, actually, name_i18n;
put all your var = name, var = nation and var = lrgImg into inside the loop.
Final code:
var queryURL = "https://api.worldofwarplanes.eu/wowp/encyclopedia/planes/?application_id=demo";
$.getJSON(queryURL, function (data) {
var quantity = data.meta.count;
$('#planeQuantity').append( quantity );
for (key in data.data) {
var item = data.data[key];
var name = item.name_i18n;
var nation = item.nation;
var lrgImg = item.images.large;
$('#planes').append('<li>' + name + 'is from ' + nation + '<img src="' + lrgImg + '">' + '</li>');
}
})
Working pen: http://codepen.io/mrlew/pen/vgaexb
Edited with some explanation
You received a data Object that have a data key whose value is a huge Object with this structure (more or less):
{
"7290": { /* ... */ },
"7291": {
"name_i18n": "North American FJ-1 Fury",
"nation":"usa",
"images":{
"large":"http://worldofwarplanes....png",
/* ... */
},
/* ... */
},
"7292": { /* ... */ }
}
So, to iterate over all keys of data.data keys we can use for (key in data.data) { }.
In each iteration, key variable will be assigned to a object key: 7290, 7291, 7292. So, to access it's value, we use data.data[key] (will be data.data["7291"], for instance), and assigned the variable item with the value.
Using brackets like this is one way in JavaScript to retrieve a value from an Object. Another way is to use dot notation (but you can't use dot notation with a key that's a number).
This is valid:
data["data"]["7291"]
This is invalid:
data.data.7291
You should set the values of name, nation and lrgImg inside each. So the elements you append won't all have the same thing. And you should loop through the data object that is inside your data object (data.data). Like this:
var queryURL = "https://api.worldofwarplanes.eu/wowp/encyclopedia/planes/?application_id=demo";
$.getJSON(queryURL, function (data) {
var quantity = data.meta.count;
$('#planeQuantity').append( quantity );
$.each(data.data, function(key, value){
var name = value.name_i18n; // get the name of this data entry
var nation = value.nation; // get the nation of this data entry
var lrgImg = value.images.large; // ...
$('#planes').append('<li>' + name + 'is from ' + nation + '<img src="' + lrgImg + '">' + '</li>');
});
});
var queryURL = "https://api.worldofwarplanes.eu/wowp/encyclopedia/planes/? application_id=demo";
$.getJSON(queryURL, function (data) {
var quantity = data.meta.count;
$('#planeQuantity').append( quantity );
$.each(data.data, function(i, e) {
var name = e.name_i18n;
var nation = e.nation;
var lrgImg = e.images.large;
$('#planes').append('<li>' + name + 'is from ' + nation + '<img src="' + lrgImg + '">' + '</li>');
});
});
You need to iterate through data.data object. Since you aren't working with dom nodes use $.each() instead of $.fn.each()
$.each(data.data, function(key, obj){
console.log(key) // "4101"
console.log(obj.name) // "type=91"
})
Related
I have an ajax call that returns a Serialized JSON string with various keys and values within it, I want to loop through these values and assign each individual key and value to a different label, I already have 8 labels set up. (I am quite new to Javascript so any help or constructive feedback would be greatly appreciated)
Haven't tried much as I am quite new to JavaScript
var obj = response.ret.SearchCriteria;
var resultJSON = obj;
var result = $.parseJSON(resultJSON);
var count = Object.keys(result).length;
for (i = 1; i < count; i++) {
var c = $('#lbl' + [i]);
$.each(result, function(k, v) {
c.text(k + ' is ' + v);
});
};
I have 6 labels and the last item of the JSON array (String) is displayed in each label
I believe your issue is why only last item of JSON array is being displayed in each label.
This is because of c.text(k + ' is ' + v).
Here the existing text content is replaced with every iteration of 'each' loop
Instead, you can consider doing this, which will append existing content as well with $.each loop.
c.text(c.text() + k + ' is ' + v)
OR
Simply
c.append( k + ' is ' + v)
If I am wrong in my assumption, please describe your scenario more, so that we can help you out :)
I want to sort the items by the one closest to the user, currently showing them but sorted by id (default). I have managed to sort them through sort but it does not seem to work.
My code JS:
$(function() {
$.getJSON('clients?transform=1', function(data) {
$.each(data.clients, function(i, f) {
var distance = getDistanceFromLatLonInKm(position.latitude,position.longitude,f.Latitude,f.Longitude).toFixed(1);
var tblRow = "<li>" + "<div class='distance'>" + distance + "</div>" + "<span>" + f.nombre + "</span>" + "</li>";
$(tblRow).sort(function(a, b){return a-b;}).appendTo("#cercademi");
});
});
});
In my html, no order by distance. Im tried in several ways.
Note: this project actually works in angularjs 1.5.8 and js.
You need to first calculate all distances and only then perform the sort (and only once). I would in fact extend the f object with a distance property, and then chain the sort to the list of such mutated objects.
Some other remarks:
the $.map callback will get the array value as first argument, not as second.
the JSON you receive has a clientes property, not clients
Working snippet (with dummy getDistanceFromLatLonInKm function and position):
$(function() {
var position = {}; // actual position is not important for this demo
$.getJSON("https://viveenunclick.com/api.php/clientes?transform=1", function (data) {
$("#cercademi").append(
$.map(data.clientes, function(f) {
f.distance = getDistanceFromLatLonInKm(position.latitude,
position.longitude,f.Latitude,f.Longitude);
return f;
}).sort(function(f1, f2) {
return f1.distance - f2.distance;
}).map(function (f) {
return "<li><div class='distance'>" + f.distance.toFixed(1) + "</div>" +
"<span>" + f.nombre + "</span></li>";
})
);
});
});
// Dummy implementation, just to make it work
function getDistanceFromLatLonInKm() {
return Math.random() * 10000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<ul id="cercademi"></ul>
I'm using the following code/data to display a list of our top-earning students in each House.
The data
Attachment 1: User_Info is an array of Objects
Attachment 2: User_Info is an array of Objects such as this
Attachment 3: Database_Info is an Object like this
The code
HPAnalysisObject.dispHPTotals = function(User_Info, Database_Info) {
// See attachments 1 and 2
console.log(User_Info);
// See attachment 3
console.log(Database_Info);
// "label" is just a text title, like "Eagles"
var html = '<h2>' + HPAnalysisObject.label + '</h2>' +
// "TotalPoints" is an integer figure
'<div id="total">' + Database_Info.TotalPoints + '</div>';
// create the table to display
html += '<table><tr><th class="name">Name</th><th class="points">Points</th></tr>';
// use "for, in" to access the value of the object key (which is the user's ID)
for (var id in Database_Info.UserDetails) {
html += '<tr>';
for (var i = 0; i < User_Info.length; i++) {
if (User_Info[i].id == id) {
// if the User_Info and Database_Info objects match up on the User's ID, add table cells to our html variable
html += '<td class="name">' + User_Info[i].firstname + ' ' + User_Info[i].surname + '</td><td class="points">' + Database_Info.UserDetails[id] + '</td>';
}
}
html += '</tr>';
}
html += '</table>';
$('div#display').html(html);
};
The problem
Oddly, in Firefox, these students display in the correct numerical order, as the students are received from my PHP script.
However, in Google Chrome and Internet Explorer, they appear in a seemingly-random order!
My first thought was to order the object, but having read a few questions on here, it seems like ordering objects isn't the best practice.
Can I rewrite this code so that I display the same tabular data - just in the right order on every browser?
Thanks in advance,
In most languages, you cannot assume that object attributes occur in any particular order.
One solution might be to add an accessor to each entry in UserDetails such as:
UserDetails={
ID:{
accessor:1,
id: ID
}
}
And then sort the records on UserDetails[ID].accessor.
Another might be to construct UserDetails as an array of elements which encode key values as "key:value", splitting each retrieved elements on /:/ as in:
[
"90030:87"
...
]
EDIT
Assuming
var userDetails={
a:{i:3,key:'third'},
b:{i:1,key:'first'},
c:{i:2,key:'second'}
};
where i is the accessor, you can create a sorted array of objects using
var sortedObjs=Object.keys(userDetails)
.map(function(k){ return userDetails[k] })
.sort(function(left,right){ return left['i']-right['i'] });
which extracts keys from userDetails, creates an array of the keyed elements via map and sorts the resulting elements by their accessor value such that
console.log(sortedObjs.map(function(elt){return elt.key}).join(','))
will print to the console:
first,second,third
Objects are an unsorted mapping of keys to values, their order is never guaranteed.
When I get anything like this, I like to build an array using the ID as numeric keys. For instance, something like this in PHP:
$out = Array();
while($row = database_get_row($set)) { // replace with your choice of database library
$out[$row['id']] = $row;
}
ksort($out);
$out = array_values($out);
In this way, you can ensure that the array is in order of increasing ID, and then pass that array to JavaScript for use in a for(i=0;i<l;i++) loop.
You'll have to sort Database_Info.UserDetails using an array wrapper:
// test data using same data as example but with no order
var Database_Info = {
UserDetails : {
137473 : 87,
90132 : 126,
90057 : 79,
90030 : 87,
90095 : 82
}
}
var objWrapper = [];
for (key in Database_Info.UserDetails) {
objWrapper.push(key);
}
objWrapper.sort(); // default sort = numeric order ascending
for (a = 0, b = objWrapper.length; a < b; a++) {
var userInfo = Database_Info.UserDetails[objWrapper[a]];
// do something interesting
console.log(userInfo);
}
I decided to wrap my Objects in a sortable array. This appeared to do the trick.
HPAnalysisObject.dispHPTotals = function(User_Info, Database_Info) {
// make a sortable array
var Combined_Info = [];
// "label" is just a text title, like "Eagles"
var html = '<h2>' + HPAnalysisObject.label + '</h2>' +
// "TotalPoints" is an integer figure
'<div id="total">' + Database_Info.TotalPoints + '</div>';
// create the table to display
html += '<table><tr><th class="name">Name</th><th class="points">Points</th></tr>';
// use "for, in" to access the value of the object key (which is the user's ID)
for (var id in Database_Info.UserDetails) {
for (var i = 0; i < User_Info.length; i++) {
if (User_Info[i].id == id) {
var StudentInfo = { name: User_Info[i].firstname + ' ' + User_Info[i].surname, points: Database_Info.UserDetails[id] };
Combined_Info.push(StudentInfo);
}
}
}
Combined_Info.sort( function(a, b) {
return b.points - a.points;
});
for (var i = 0; i < Combined_Info.length; i++) {
html += '<tr>';
html += '<td class="name">' + Combined_Info[i].name + '</td><td class="points">' + Combined_Info[i].points + '</td>';
html += '</tr>';
}
html += '</table>';
$('div#display').html(html);
};
I'm looking to loop through a JSON array and display the key and value.
It should be a simplified version of the following post, but I don't seem to have the syntax correct: jQuery 'each' loop with JSON array
I also saw the post Get name of key in key/value pair in JSON using jQuery?, but it also seemed like lots of code for a simple activity.
This illustrates what I'm looking for (but it doesn't work):
var result = '{"FirstName":"John","LastName":"Doe","Email":"johndoe#johndoe.com","Phone":"123 dead drive"}';
$.each(result, function(k, v) {
//display the key and value pair
alert(k + ' is ' + v);
});
There is no mandatory jQuery requirement, but it is available. I can also restructure the JSON if it cuts down the required code.
You have a string representing a JSON serialized JavaScript object. You need to deserialize it back to a JavaScript object before being able to loop through its properties. Otherwise you will be looping through each individual character of this string.
var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"johndoe#johndoe.com","Phone":"123 dead drive"}';
var result = $.parseJSON(resultJSON);
$.each(result, function(k, v) {
//display the key and value pair
alert(k + ' is ' + v);
});
Live demo.
var obj = $.parseJSON(result);
for (var prop in obj) {
alert(prop + " is " + obj[prop]);
}
You can get the values directly in case of one array like this:
var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"johndoe#johndoe.com","Phone":"123 dead drive"}';
var result = $.parseJSON(resultJSON);
result['FirstName']; // return 'John'
result['LastName']; // return ''Doe'
result['Email']; // return 'johndoe#johndoe.com'
result['Phone']; // return '123'
The following should work for a JSON returned string. It will also work for an associative array of data.
for (var key in data)
alert(key + ' is ' + data[key]);
Parse the JSON string and you can loop through the keys.
var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"johndoe#johndoe.com","Phone":"123 dead drive"}';
var data = JSON.parse(resultJSON);
for (var key in data)
{
//console.log(key + ' : ' + data[key]);
alert(key + ' --> ' + data[key]);
}
The best and perfect solution for this issue:
I tried the jQuery with the Ajax success responses, but it doesn't work so I invented my own and finally it works!
Click here to see the full solution
var rs = '{"test" : "Got it perfect!","message" : "Got it!"}';
eval("var toObject = "+ rs + ";");
alert(toObject.message);
whats wrong with this jquery code. it is not outputting anyting?
var imagesToLoad = [];
var name = 'hi';
var src = 'ho';
imagesToLoad[name] = src;
$.each(imagesToLoad, function(index, value) {
alert(index + ': ' + value);
});
basically i want to add custom variables to my object after it has been created.
Javascript arrays don't support non numerical indexes. You probably want to use an object instead:
var imagesToLoad = {};
imagesToLoad.hi = 'ho';
$.each(imagesToLoad, function(index, value) {
alert(index + ': ' + value);
});
You should check the doc for $.each method - it accepts only callback function as parameter and it can iterate only over jQuery object