Access data from Object in json response - javascript

My json returns below shown set of array of objects and I need to access the data inside it. In the console this is what the response looks like
What i am trying to do is to access the object to get the subcategoryid and subcategoryname then display it inside a dropdown list. Here is my code for it
$.get('ajax-subcat?cat_id=' + cat_id, function(data)
{
console.log(data);
$('#subcategory').empty();
$.each(data, function(index, subcatObj)
{
alert(subcatObj);
$('#subcategory').append('<option value="' + subcatObj.Object.subcategoryid +'">' + subcatObj.subcategoryname +'</option>');
});
});
The thing I don't know is how to access the data inside the object. Any ideas?

Try this:
JAVASCRIPT
for (var i = 0; i < data.length; i++) {
console.log(data[i].subcategoryid);
}

Assuming that you have a select element in markup:
<select id="mySelectElement"></select>
Try this to iterate the object and fill the combo box:
$.get('ajax-subcat?cat_id=' + cat_id, function(data) {
// Get a reference to the target element
var selectTarget = $('#mySelectElement');
// Iterate over the response data
for (var i in data) {
// For every object in array, append a new option element
selectTarget.append($('<option value="' + data[i].subcategoryid + '">' + data[i].subcategoryname + '</option>'));
}
});

For this purpose, you can use underscore.js library to get whole data corresponding to particular key in the form of array.
_.pluck(data, 'subCategoryid') // array of all values corresponding to 'subcategoryid'

Related

Looping through each item from JSON to display plane information

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"
})

Jquery binding loop variable to getJSON function

I have a for loop that GETs a json array and populates it in a table along with another list's variables. My problem is I am not able to access i inside the get method. But I have mylist and all its contents inside. I tried binding the function to a variable i using bind(this,i) but that says .getJSON() is not a function. Here's the relevant code.
var mylist = ["a", "b", "c"]
for (i = 0; i < mylist.length; i++) {
urlstr = "/" + mylist[i]; // Generate url
$.getJSON(urlstr, function(data) {
html = "<tr><td>" + mylist[i] + "</td><td>" + data.string[0] + "</td></tr>";
$("#tableresult").append(html); //this returns undefined for mylist[i]
console.log(i); //this returns 3 which is the length of list
});
}
In short I need the variables outside getJSON be accessible within getJSON.
Can someone please help? Thanks and regards.
This should be no different from binding the loop variable in practically any other loop. Since you are working with an array, the cleanest approach is to use Array#forEach:
var mylist = ["a", "b", "c"];
mylist.forEach(function (item) {
var urlstr = "/" + item;
$.getJSON(urlstr, function(data){
var html = "<tr><td>" + item + "</td><td>" +
data.string[0] + "</td></tr>";
$("#tableresult").append(html);
console.log(item);
});
});
please ensure your php return data is json.
for example:
$data['something'] = 'data';
echo json_encode($data);
and using function for get index (i):
$.getJSON("demo_ajax_json.js", function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});

How to insert a json object into an unordered list

I have a json object that i created using obj = JSON.parse(data). "data" was recieved from a webserver. I know the object is correct because i can print single variables from it into a div or my list.
This is what is the json object is created from:
[{"name":"Staurikosaurus","group":"Saurischia","diet":"Carnivore","period":"Triassic"},{"name":"Diplodocus","group":"Saurischia","diet":"Herbivore","period":"Jurassic"},{"name":"Stegosaurus","group":"Ornithischia","diet":"Herbivore","period":"Jurassic"},{"name":"Tyrannosaurus","group":"Saurischia","diet":"Carnivore","period":"Cretaceous"}]
Literally all i want to do is put this into a to show up on a web page.
My current code:
function getJson(){$.get(MY URL, function(data) {
// String
//console.dir(data);
// Parse JSON
var obj = JSON.parse(data);
// JSON object
//console.dir(obj);
$('#myList').html("<li>"+obj[0].period+"</li><li>"+obj[2].period+"</li>");
//$('#myList').html("<li>obj[2].period</li>");
});
}
This successfully prints out the list with Triassic then Jurrasic.
I would prefer to do this in Jquery but javascript is okay.
Thank You.
You are not iterating through the list, just printing out the 0-th and 2nd element in the array. Try:
function getJson(){$.get(MY URL, function(data) {
// String
//console.dir(data);
// Parse JSON
var obj = JSON.parse(data);
// JSON object
//console.dir(obj);
var inner = '';
for(i=0; i < obj.length; i++) {
inner += "<li>"+obj[i].period+"</li>";
}
$('#myList').html(inner);
});
}
I'm sure there's a cleaner way using jQuery but that should work
If you're want to use the jQuery syntax, process like this:
var listElement = '';
$.each(obj, function(index, value) {
listElement += '<li>' + data[obj].period + '</li>';
})
$('#myList').html(listElement);

Populate database with json in JavaScript

I have a JSON String in a JavaScript var, how I can loop through JSON string to make script like this output?
INSERT INTO table VALUES ('$var1', '$var2', '$var3', '$varN');
Is there is any direct way to fill a table from a json string?
JSON Example:
{"table":[{"id":"1","name":"David","nick":"falk","year":"20"},{"id":"2","name":"Mark","nick":"master","year":"50"},{"id":"3","name":"jhon","nick":"jx","year":"20"},{"id":"4","name":"Maria","nick":"beauty","year":"20"}]}
We assign a variable name to the json object
var table = {"table":[{"id":"1","name":"David","nick":"falk","year":"20"},{"id":"2","name":"Mark","nick":"master","year":"50"},{"id":"3","name":"jhon","nick":"jx","year":"20"},{"id":"4","name":"Maria","nick":"beauty","year":"20"}]};
Using jquery
loop over the variable table which have the property table.
$.each(table.table,function(index, item){
//INSERT INTO table VALUES ('$var1', '$var2', '$var3', '$varN');
console.log("INSERT INTO table VALUES('"+ item.id + "','"+ item.name + "','"+ item.nick + "','"+ item.year +"')");
});
take a look in jsfiddle http://jsfiddle.net/628Cb/
You can use the for loop to iterate over the array contained by the table object.
var p = {"table":[{"id":"1","name":"David","nick":"falk","year":"20"},{"id":"2","name":"Mark","nick":"master","year":"50"},{"id":"3","name":"jhon","nick":"jx","year":"20"},{"id":"4","name":"Maria","nick":"beauty","year":"20"}]};
var arr = p["table"];
for(var i=0;i<arr.length;i++){
var obj = arr[i];
alert(obj["id"] + " "+ obj["name"] + " "+ obj["nick"]+ " "+obj["year"]);
INSERT INTO table VALUES (obj["id"], obj["name"], obj["nick"], obj["year"]);
}

Populating Select Combobox Form from external CSV file

I'm using this code to import a CSV into a var using ajax, then, split the informatión delimited by the "\n" and then populate a Select Box I have in a form.
The CSV is pretty much flat, just 1 column with several rows. Added an alert to monitor the progress.. it all goes fine except when it comes to populate the combobox, instead of populating the String Content, it populates the number of row, for some reason the array is not recording string but row number.
<script>
$.ajax({
url: 'URL CSV',
success: function(data) {
alert(data);
var splitData=data.split("\n");
for(pn in splitData){
alert(splitData);
$('#Entry_ID').append("<option value=\""+pn+"\">"+pn+"</option>");
}
}
});
</script>
(the form combobox code)
<select name="Entry.ID" id="Entry_ID" aria-required="true"></option>
</select>
Your error is in the "for..in" loop. A code like this:
var arr = ["q", "w", "e"];
for (var i in arr) {
console.log(i)
}
will output:
0
1
2
The for..in loop takes the key of each item in the object and it is assigned to the var. In an array the key is its position.
The method split of String returns an array with all the items. To loop through the splitData array you can:
for (var i = 0; i < splitData.length; i++) {
alert(splitData[i]);
$('#Entry_ID').append("<option value=\"" + splitData[i] + "\">" +
splitData[i] + "</option>");
}
or
splitData.forEach(function (item) {
alert(item);
$('#Entry_ID').append("<option value=\"" + item + "\">" + item + "</option>");
});

Categories

Resources