I came across an exercise in freeCodeCamp to convert json data to html. Here, I was asked to copy paste a jquery which I didn't understand.
json.forEach(function(val) {
var keys = Object.keys(val);
html += "<div class = 'cat'>";
keys.forEach(function(key) {
html += "<strong>" + key + "</strong>: " + val[key] + "<br>";
});
html += "</div><br>";
});
This is my json
[
{
"id":0,
"imageLink":"https://s3.amazonaws.com/freecodecamp/funny-cat.jpg",
"altText":"A white cat wearing a green helmet shaped melon on it's head. ",
"codeNames":[
"Juggernaut",
"Mrs. Wallace",
"Buttercup"
]
},
{
"id":1,
"imageLink":"https://s3.amazonaws.com/freecodecamp/grumpy-cat.jpg",
"altText":"A white cat with blue eys, looking very grumpy. ",
"codeNames":[
"Oscar",
"Scrooge",
"Tyrion"
]
},
{
"id":2,
"imageLink":"https://s3.amazonaws.com/freecodecamp/mischievous-cat.jpg",
"altText":"A ginger cat with one eye closed and mouth in a grin-like expression. Looking very mischievous. ",
"codeNames":[
"The Doctor",
"Loki",
"Joker"
]
}
]
Can anyone help me to break down this code and tell what each line in the code does? For example I don't know what Object.keys does. Is Object an inbuilt instance?
The Object.keys() method returns an array of a given object's own enumerable properties.
var keys = Object.keys(val);
Here 'keys' is the array form of your json.
According to the JSON you provided the array has 3 objects.
You can also write
Object.keys(val).forEach(function(key){
//something
});
instead of
var keys = Object.keys(val);
keys.forEach(function(key) {
//something
});
Inside the loop the key returns the the key of your object i.e.
id, imageLink etc
and
val[key] return corresponding values e.g.
0, "https://s3.amazonaws.com/freecodecamp/funny-cat.jpg" to be more specific.
From MDN
Object.keys() returns an array whose elements are strings corresponding to the enumerable properties found directly upon object. The ordering of the properties is the same as that given by looping over the properties of the object manually.
The purpose of the code is to generate html by using key and corresponding value.
var json = [
{
"id":0,
"imageLink":"https://s3.amazonaws.com/freecodecamp/funny-cat.jpg",
"altText":"A white cat wearing a green helmet shaped melon on it's head. ",
"codeNames":[
"Juggernaut",
"Mrs. Wallace",
"Buttercup"
]
},
{
"id":1,
"imageLink":"https://s3.amazonaws.com/freecodecamp/grumpy-cat.jpg",
"altText":"A white cat with blue eys, looking very grumpy. ",
"codeNames":[
"Oscar",
"Scrooge",
"Tyrion"
]
},
{
"id":2,
"imageLink":"https://s3.amazonaws.com/freecodecamp/mischievous-cat.jpg",
"altText":"A ginger cat with one eye closed and mouth in a grin-like expression. Looking very mischievous. ",
"codeNames":[
"The Doctor",
"Loki",
"Joker"
]
}
]
var html = "";
//iterating through all the item one by one.
json.forEach(function(val) {
//getting all the keys in val (current array item)
var keys = Object.keys(val);
//assigning HTML string to the variable html
html += "<div class = 'cat'>";
//iterating through all the keys presented in val (current array item)
keys.forEach(function(key) {
//appending more HTML string with key and value aginst that key;
html += "<strong>" + key + "</strong>: " + val[key] + "<br>";
});
//final HTML sting is appending to close the DIV element.
html += "</div><br>";
});
document.body.innerHTML = html;
Related
I'm grabbing a list of elements ids thusly.
var menus = $(".menu").map(function(){
return this.id;
});
Which returns something like:
["lunch", "appetizers", "soup", "salads", "seafood", "noodles", "stir_fry", "curry", "kids", "steak", "dessert", "sides"]
For each item in the array I want to grab some JSON data.
$.each(menus,function(i) {
var list = menus[i],
meal = data.menu.list,
items = '<li><h3>' + meal.name + '</h3><p>' + meal.desc + '</p></li>';
$('#'+list+".menu").append(items);
});
Such that data.menu.list would be data.menu.lunch, data.menu.appetizers, etc.
The JSON is structured like so:
{
"menu": {
"lunch": [{
"name": "Kao PAdd",
"desc": "Fried rice with onions, green onions, snow peas, and egg / Chicken, vegetarian / Shrimp or tofu (Add $1)"
}
Any thoughts that don't involve eval()?
EDIT:
I when I do this:
$.each(data.menu,function(i) {
console.log(data.menu[i].key);
});
the console gives me:
Object {lunch: Array(14), appetizer: Array(11)}
All I really want is to access those arrays.
console.log(data.menu[i].name)
gives me a pair of undefineds.
That’s a brilliant question, Sir!
No matter how you retrieve your menus, strToVar() will do the task.
This code converts strings from array to variable names:
Solution:
var strToVar = (str,val) => this[str] = val;
Example:
var menus = ["lunch", "appetizers", "soup", "salads", "seafood", "noodles",
"stir_fry", "curry", "kids", "steak", "dessert", "sides"];
menus.forEach(strToVar);
prompt("[lunch, appetizers, soup, salads, seafood, noodles, " +
"stir_fry, curry, kids, steak, dessert, sides]",
[lunch, appetizers, soup, salads, seafood, noodles,
stir_fry, curry, kids, steak, dessert, sides]);
Give me all your points.
If you're looking for parsing JSON string to object here you go:
var jsonString = '{"data":{"item":{"id":1,"value":"foo"}}}';
var jsonObj = JSON.parse(jsonString);
console.log(jsonObj.data.item.value);
The problem was, I didn't understand what I really wanted to do. I asked the wrong question (although it's an interesting one, so I'll leave it up).
I thought I needed to generate my variable list from the HTML ids, but that was a mistake. What I needed was simply another for loop (or jQuery each());
$.each(data.menu, function(i) {
var list = data.menu[i],
menus = [];
$.each(list, function(x) {
var items = '<li><h3>' + list[x].name + '</h3><p>' + list[x].desc + '</p></li>';
menus.push(items)
});
$('#' + i).append(menus);
});
Your $.each function should be:
$.each(menus, function(i, list) { // the second parameter is list so we don't need menus[i]
var meal = data.menu[list], // use of bracket notation
items = '<li><h3>' + meal.name + '</h3><p>' + meal.desc + '</p></li>';
$('#' + list).append(items);
// ^^^ no need for the ".menu" as IDs alone are sufficient (assuming you have unique IDs, otherwise you have a problem)
});
Docs on MDN for bracket notation.
As per my understanding you want to achieve something like this :
var menus = ["lunch", "appetizers", "soup", "salads"];
var menuList = [
{
"name":"lunch",
"description":"description1"
},
{
"name":"appetizers",
"description":"description2"
},
{
"name":"soup",
"description":"description3"
},
{
"name":"salads",
"description":"description4"
}
]
var menu = {};
for(var i in menus) {
menu[menus[i]] = [{
"name": menuList[i].name,
"desc": menuList[i].description
}];
}
console.log(menu);
found a code snippet i am trying to modify but i can't seem to get it to work, This code is made to parse the json format as such
[
{
"name":"Barot Bellingham",
"shortname":"Barot_Bellingham",
"reknown":"Royal Academy of Painting and Sculpture",
"bio":"Barot has just finished his final year at The Royal Academy of Painting and Sculpture, where he excelled in glass etching paintings and portraiture. Hailed as one of the most diverse artists of his generation, Barot is equally as skilled with watercolors as he is with oils, and is just as well-balanced in different subject areas. Barot's collection entitled \"The Un-Collection\" will adorn the walls of Gilbert Hall, depicting his range of skills and sensibilities - all of them, uniquely Barot, yet undeniably different"
}
]
and my json format is multilevel nested such as
{
"data": [
{
"artists": {
"Artist": "Muse"
}
},
{
"artists": {
"Artist": "Coldplay"
}
}
]
}
The Javascript i found is
$('#search').keyup(function(){
var searchField = $('#search').val();
var myExp = new RegExp(searchField, 'i');
$.getJSON('data.json', function(data){
var output = '<ul class="searchresult">';
$.each(data, function(key, val){
if((val.name.search(myExp) != -1) || (val.bio.search(myExp) != -1)) {
output +='<li>';
output +='<h2>' + val.name + '</h2>';
output +='<img src="images/' + val.shortname + '_tn.jpg" alt="'+ val.name +'" />';
output +='<p>' + val.bio + '</p>';
output +='</li>';
}
});
output += '</ul>';
$('#update').html(output);
});
});
So how and where would i modify this to sort through my json format?
Thanks!
The response data is an object with a property data that contains an array, which you should loop over with $.each(). Each element is an object with an artists property, and its value is an object with an Artist property (I don't know why they have this extra level of nesting, it seems redundant).
$.each(data.data, function(index, val) {
var artist = val.artists.Artist;
// do what you want with artist
});
Following is the JSON array, I want to get number of parent objects and then run for loop on them to get each object value.
It should give total count 2 as I have two parent objects - canvas0 and canvas1.
{"canvas0":
"{"objects":
[{"type":"textbox","originX":"left","originY":"top","left":40,"top":350,"width":200,"height":20.97,"fill":"black","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","fillRule":"nonzero","globalCompositeOperation":"source-over","text":"ADDRESScanvasPage1","fontSize":16,"fontWeight":"normal","fontFamily":"Helvetica","fontStyle":"","lineHeight":1.16,"textDecoration":"","textAlign":"center","textBackgroundColor":"","styles":{},"minWidth":20}],"background":""}"
,"canvas1":"{"objects":[{"type":"textbox","originX":"left","originY":"top","left":40,"top":350,"width":200,"height":20.97,"fill":"black","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","fillRule":"nonzero","globalCompositeOperation":"source-over","text":"ADDRESScanvasPage2","fontSize":16,"fontWeight":"normal","fontFamily":"Helvetica","fontStyle":"","lineHeight":1.16,"textDecoration":"","textAlign":"center","textBackgroundColor":"","styles":{},"minWidth":20}],"background":""}"}
As everyone said, your JSON is invalid. The same valid JSON in minimal would look like the following.
var json = {
"canvas0": {
"objects": [
{
"type": "textbox",
"originX": "left"
}
],
"background": "#000"
},
"canvas1": {
"objects": [
{
"type": "select",
"originX": "right"
}
]
}
};
To be able to iterate thru, you don't need the count of top level keys. And moreover, a JSON object doesn't have the length property. All you need to do is, use for...in loops and display the key/values accordingly. Here is an example of how you can do it. Bear in mind that this only works with your specific case as the loop needs changing as and when the JSON levels change.
alert ( "Length of top level keys: " + Object.keys(json).length );
for (var key in json) {
var canvas = json[key];
for (var key2 in canvas) {
if (canvas[key2] instanceof Array) {
var object = canvas[key2][0];
for (var key3 in object) {
alert (key3 + ": " + object[key3]);
}
} else {
alert (key2 + ": " + canvas[key2]);
}
}
}
Here is a working demo with the complete code.
I am beginning a exercise to create a quiz in javascript. Anyway, I have an array which contains the questions; each question is a anonymous object...
var allQuestions = [{
"question": "Who was Luke's wingman in the battle at Hoth?",
"choices": ["Dak", "Biggs", "Wedge", "fx-7"],
"correctAnswer": 0},
{
"question": "What is the registry of the Starship Reliant?",
"choices": [ "NX-01", "NCC-1864", "NCC-1701", "NCC-2000"],
"correctAnswer": 1}...etc.
At this point i'd like to simply iterate through them and insert them into the DOM.
var output = '';
for (key in allQuestions[0]) {
output += '<li>' + allQuestions[0] + '</li>';
}
var update = document.getElementById("question");
update.innerHTML = output;
But all I get is:
[object Object]
[object Object]
[object Object]
At some point i'd like to match or have 'question', 'choices' flow in to corresponding elements on the page....
<h2>question</h2> //question from object
<ul id="question">
<li>choice</li> //choice from object
<li>choice</li>
<li>choice</li>
<li>choice</li>
You're using allQuestions[0] inside the loop, but you probably meant to refer to key:
for (key in allQuestions[0]) {
output += '<li>' + key + '</li>';
}
However, this will return question, choices, correctAnswer. If the items in allQuestions are in the same format you're better off looping over them and referring to the relevant properties:
for (var i = 0; i < allQuestions.length; i++) {
var item = allQuestions[i];
console.log(item.question);
console.log(item.choices);
// etc.
}
I have the following javascript array:
[{
"id": "115",
"poster": "809",
"post": "alfa"
}, {
"id": "127",
"poster": "808",
"post": "beta"
}]
What do I need to do in order to extract the values into usable variables?
Try this,
var arr = [{"id":"115","poster":"809","post":"alfa"},{"id":"127","poster":"808","post":"beta"}];
for (i = 0; i < arr.length; i++)<br/>
document.write("id: " + arr[i].id + " poster: " + arr[i].poster + " post: " + arr[i].post + "<br/>");
What you have is an array with two elements
data = [a,b]
where both elements a and b are objects each having three fields (id,poster,post).
Recall that to access an element in the array at position i you simply write data[i] (this will access the ith element in your array i.e. one of the objects).
In order to access a field of the object a you simply use a.fieldName. For example a.id will access id field of object a. If you combine them both you can get data[i].fieldName to access field of specific object (for example data[0].id will return "115").
As a side note, array structures are iterable:
for(var i = 0;i<data.length;i++){
id = data[i].id;
post = data[i].post;
poster = data[i].poster;
document.write(id+" "+post+" "+poster+"<br/>");
}
UPDATE: Example on jsFiddle