JSON Loop through nested array - javascript

This is my JS ("data" is from the json call):
if (data.projectReports.length) {
for (var i in data.projectReports){
var report = data.projectReports[i];
$('#reports').append(
'<div class="report-description">' +
'<h2>' + report.header + '</h2>' +
'<p>' + report.text + '</p>' +
'</div>' +
'<ul class=\"report-moreinfo\">' +
// I want to loop through "persons" here.
'</ul>'
);
}
} else
. . .
This is my JSON:
{
"projectReports":[
{
"header":"Headline",
"text":"Description of item",
"estimate":10,
"actual":7,
"persons":{
"Robert":5,
"Erik":10,
"Juan":3
}
}
]
}
I am new to JSON and after searching for an answer and actually finding a few different answers, new problems arose so I thought I would post the question in it's entirety here.
Where the comment is in my JavaScript code, I want to loop through report.persons.
In all of the solutions I found they could point directly to "header" or "text" like I have done before, but in this case I just have a key and value. How would I go about doing something like this?
<li><p> persons.key </p><p> persons.value </p></li>
I understand that I will have to do another for loop, but my knowledge isn't good enough to be able to figure out on my own how to construct it.

This is pretty basic stuff
var personsMarkup = "";
for (var i in persons){
if (persons.hasOwnProperty(i)){
console.log(i); // the key
console.log(persons[i]); // the value
// cancat this all together
personsMarkup =+ "<li><p>"+i+"</p><p>"+persons[i]+"</p></li>";
}
}
and then:
$('#reports').append(
/* ... */
'<ul class=\"report-moreinfo\">' +
personsMarkup +
'</ul>';
/* ... */
);

For your code I'd use a function that loops through reports.persons and returns what you need:
var showPersons = function(persons){
var appendedData = '';
for (var person in persons) {
if (!persons.hasOwnProperty(person)) continue;
appendedData += '<li><p>' + person + '</p><p>' + persons[person] +'</p></li>'
}
return appendedData;
};
And now you can use this to append all that stuff inside the <ul> tags:
listPersons(report.persons);
If you wanted the code read closer to what you wanted (and to be able to use person.name and person.value), you'd need to have the JSON in this format:
{
"projectReports": [
{
"header": "Headline",
"text": "Description of item",
"estimate": 10,
"actual": 7,
"persons": [
{
"name": "Robert",
"value": 5
},
{
"name": "Erik",
"value": 10
},
{
"name": "Juan",
"value": 3
}
]
}
]
}

Use for (.. in ..)
$('#reports').append(
'<div class="report-description">' +
'<h2>' + report.header + '</h2>' +
'<p>' + report.text + '</p>' +
'</div>' +
'<ul class=\"report-moreinfo\">');
for (var personKey in report.persons){
$('#reports').append('<li><p>' + personKey + '</p><p>' + report.persons[personKey] + '</p></li>');
}
$('#reports').append(
'</ul>'
);

Related

JSON parse variable result

I have a JSON which I query with xhr. The objects (person) contain a key-value pair called "serviceLevel" that I have to split.
When I stack this in a variable (services) and log it like this:
let main = document.getElementsByTagName('main');
getXHR("GET", './db/orga.json', (success) => {
format(success)
}, (error) => {
console.error(error)
});
function format() {
let people = arguments[0];
for (let i in people) {
let person = people[i];
let services = person.serviceLevel.split(".");
console.log(services);
console.log(person.serviceLevel.split("."));
let idCard = document.createElement('div');
idCard.id = person.firstName + person.familyName;
idCard.classList.add('person');
idCard.innerHTML = "<div class=\"item nom\"><span class=\"prenom\">" + person.firstName + "</span><span class=\"famille\">" + person.familyName + "</span></div>";
idCard.innerHTML += "<span class=\"job\">" + person.jobTitle_1 + "</span>";
idCard.innerHTML += "<span class=\"mail\"><a href=\"mailto:" + person.mail + "\">" + person.mail + "</span>";
idCard.innerHTML += "<span class=\"tel\"><a href=\"tel:" + person.phone_1 + "\">" + person.phone_1 + "</span>";
idCard.innerHTML += "<span class=\"tel\"><a href=\"tel:" + person.mobile + "\">" + person.mobile + "</span>";
for (let j in services) {
let serviceElement = document.getElementById(services[j]);
if (!serviceElement) {
let serviceElement = document.createElement('div');
serviceElement.id = services[j];
serviceElement.classList.add('n' + j, "service");
serviceElement.innerHTML = "<span class=\"title\">" + services[j] + "</span>";
if (j == 0) {
if (services[services.length - 1] = j) {
serviceElement.appendChild(idCard);
main[0].appendChild(serviceElement);
}
} else {
let parent = services[j - 1],
parentService = document.getElementById(parent);
if (services[services.length - 1] = j) {
serviceElement.appendChild(idCard);
}
parentService.appendChild(serviceElement);
}
} else {
serviceElement.appendChild(idCard);
}
}
}
}
const data = [{
"Tri": "blablablabla, CSMSI.SAFS, n, XXXX, YYYY",
"Department": "The best department",
"serviceLevel": "CSMSI.SAFS",
"organisationLevel": "blablablabla",
"rang": "n",
"familyName": "XXXX",
"firstName": "YYYY",
"jobTitle_2": "Directeur",
"jobTitle_1": "Directeur",
"phone_1": "nn nn nn nn nn",
"phone_2": "",
"mobile": "nn nn nn nn nn",
"mail": "xxxx.yyyy#zzzz.fr",
"location": "france"
}];
format(data);
The results are different:
(2) ["CSMSI", "SAFS"]
0: "CSMSI"
1: "SAFS"
length: 2
(2) ["CSMSI", "SAFS"]
0: "CSMSI"
1: "1"
length: 2
As we can see, content of "services" are good, but when I extend the tree, the value of the second key value is "1" ... which is a problem. Is there a way to change this?
when I use a for loop with "classical" (i = 0; i < people.length; i++), i don't have the problem....

.Animate() on dynamically generated content

I am creating a website where I append progress-bar to div from JSON file.
Everything is working fine, but I can't figure out how to animate all progress-bar with their own value.
These values are loaded from the JSON file and I am only able to animate them all to one value not to their own one.
Code :
$.getJSON( "skills.json", function(data){
Skills = data;
$.each(Skills, function (title, val) {
var markup = "<div class='progress-item'>";
markup += "<span class='progress-title'>" + val.title + "</span>";
markup += "<div class='progress'>";
markup += "<div class='progress-bar'" + "style=width:" + val.value + "%" + ">" + "<span class='progress-percent'>" + val.value + "%" + "</span></div>";
markup += "</div>";
markup += "</div>";
$('.progress-wrapper').append(markup);
});
});
So this generates 3 progress-bar cause I have 3 values in my JSON file.
I tried something like :
$(".progress-bar").animate({width: val.value +"%"});
But it change the width of all my progress-bar even if they got all different in the JSON object.
JSON file :
[{
"title": "Skill 1",
"description": "Skill 1 description",
"value": 100
},
{
"title": "Skill 2",
"description": "Skill 2 description",
"value": 50
}
]
Thanks in advance for the help

How to parse json with javascript/jquery if content matches string

I currently have a json file of people taking part in a series of charity events in the following format:
[
{
"FirstName": "Anushka",
"Country": "UK",
"Day": "13/10/2017"
},
{
"FirstName": "Alessandra",
"Country": "IT",
"Day": "16/10/2017"
},
{
"FirstName": "Clare",
"Country": "US",
"Day": "13/10/2017"
}
]
I want to build a simple HTML list using this data, so that under each date, the name and country are displayed like:
<div id="13102017">
<h1>13/10/2017</h1>
<div class="col-sm-4"><p>Anushka, UK</p></div>
<div class="col-sm-4"><p>Clare, US</p></div>
</div>
<div id="16102017">
<h1>16/10/2017</h1>
<div class="col-sm-4"><p>Alessandra, IT</p></div>
</div>
I've new to JSON and so far I have figured out how to get Name and Country onto the page, but I cannot figure out how to use an if statement to only output if date = 13/10/2017 for example.
Here's what I've got so far:
$( document ).ready(function() {
$.getJSON("URL_HERE", function(data) {
$.each(data, function(i, item) {
$('#13102017').append('<div class="col-sm-4"><p>' + item.FirstName + ", " + item.Country + '</p></div>');
});
});
});
Obviously the above is currently just outputting every single name into the #13102017 section. I know I probably need an IF in there somewhere but I'm otherwise stumped. Any pointers would be much appreciated!
On each loop, check first if the date div exists, and if not, create it. Then append the info to that div...
$.getJSON("URL_HERE",function(data) {
$.each(data, function(i,item) {
var dateId = item.Day.replace(/\//g,'');
if (!$('div#'+dateId).length)
$('body').append('<div id="'+dateId+'"><h1>'+item.Day+'</h1></div>');
$('div#'+dateId).append('<div class="col-sm-4"><p>' + item.FirstName + ", " + item.Country + '</p></div>');
});
});
For array loops, I personally prefer to use for (is faster than jquery each)...
$.getJSON("URL_HERE",function(data) {
for (var i=0, l=data.length; i<l; i++) {
var item = data[i],
dateId = item.Day.replace(/\//g,'');
if (!$('div#'+dateId).length)
$('body').append('<div id="'+dateId+'"><h1>'+item.Day+'</h1></div>');
$('div#'+dateId).append('<div class="col-sm-4"><p>' + item.FirstName + ", " + item.Country + '</p></div>');
}
});
NOTE: I'm adding the date div's to the body, just change $('body') to the container where you want to put them in your page.
I would suggest you to create the whole html and then set it as html.
var data = [{
"FirstName": "Anushka",
"Country": "UK",
"Day": "13/10/2017"
},
{
"FirstName": "Alessandra",
"Country": "IT",
"Day": "16/10/2017"
},
{
"FirstName": "Clare",
"Country": "US",
"Day": "13/10/2017"
}
];
$(function() {
// You can have this inside $.getJSON
var _html = "";
data.forEach(function(item) {
_html += '<div id="' + item.Day.replace(/\//g, "") + '">' +
'<h1>' + item.Day + '</h1>' +
'<div class="col-sm-4"><p>' + item.FirstName + ", " + item.Country + '</p></div>' +
'</div>';
});
$("#container").html(_html);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
</div>
but I cannot figure out how to use an if statement to only output if
date = 13/10/2017
Simply check if item.Day == "13102017"
$( document ).ready(function() {
$.getJSON("URL_HERE", function(data) {
$.each(data, function(i, item) {
if ( item.Day == "13102017" )
{
var id = item.Day.replace( /\D/g, "" );
var html = '<div id="' id '">';
html += '<h1>' + item.Day + '</h1>';
html += '<div class="col-sm-4"><p>' + item.FirstName + '</p></div>';
html += '<div class="col-sm-4"><p>' + item.Country + '</p></div>';
html += '</div>';
$(body).append( html );
}
});
});
});

Using a for loop in Javascript to enter an object into HTML div

I'm trying to use a for-loop to reiterate over the object material and enter the material into a div on my html. Right now I have the code set to accept an array, but I'd like to use an object instead.
var animals = [
{
name:'Aye Aye',
description: 'blue',
img: 'http://cdnimg.in/wp-content/uploads/2015/06/335.jpg?cfaea8',
price:500
}, {
name:'Little Imp',
description:'yellow',
img:'http://cdnimg.in/wp-content/uploads/2015/06/334.jpg?cfaea8',
price:3000
}, {
name:'Long Nose Monkey',
decription:'grey',
img:'http://cdnimg.in/wp-content/uploads/2015/06/492.jpg?cfaea8',
price:5000
}, {
name:'Nicobar Bird',
decription:'purple',
img:'http://cdnimg.in/wp-content/uploads/2015/06/471.jpg?cfaea8',
price: 6
}, {
name:'Slow Loris',
decription: 'brown',
img: 'https://s-media-cache-ak0.pinimg.com/736x/49/09/8f/49098fbc3c9a37fb03034b45e89c5cd4.jpg',
price:90
}, {
name:'Tucan',
decription:'orange',
img: 'http://cdnimg.in/wp-content/uploads/2015/06/526.jpg?cfaea8',
price:100
}, {
name:'Fennec Fox'
decription:'yellow'
img:'http://cdnimg.in/wp-content/uploads/2015/06/526.jpg?cfaea8',
price:500
}, {
name:'Sugar Glider',
description: 'green',
img: 'https://pbs.twimg.com/media/CNd03WIUwAAqKHg.jpg:large',
price:1000000
}
]
function animal() {
// var animalName = ['Aye Aye',
var animalElement = document.getElementById("div0");
for (i=0; i<animalName.length; i++) {
animalElement.innerHTML += '<h2>' + animalName[i]+'</h2>' +'<p>' + animalDescription[i] +'</p>' + '<p>' + animalPrice[i] +'</p>' + '<p>' + animalImage[i] + '</p>';
};
};
animal();
This is a simple solution based off of what you currently have:
function generateAnimals() {
var animalElements = document.getElementById("div0");
var html = '';
for (i = 0; i < animals.length; i++) {
var animal = animals[i];
html += '<h2>' + animal.name + '</h2>'
+ '<p>' + animal.description + '</p>'
+ '<p>' + animal.price + '</p>'
+ '<p>' + animal.image + '</p>';
}
animalElements.innerHTML += html;
}
generateAnimals();
Just be warned that creating elements like this can get messy once things start to become more complex.

Bootstrap jQuery Calendar

I've found an awesome open source calendar at http://bootstrap-calendar.azurewebsites.net/index-bs3.html
I'm trying to load this project as described [link removed]
As in the demo, there is a dynamic list on the side of the calendar that does update with the events as you scroll through. How ever unlike the demo, my events are not getting listed in the calendar view. They don't show up on the calendar! :(
I did add a couple extra json data options, but the required ones weren't changed. Here's an example of my json data:
{
"success": 1,
"result": [{
"id": "########",
"title": "Event NAme",
"start_time": "2014-08-23T18:30:00-0500",
"start": "1408836600",
"end_time": "",
"end": "0",
"class": "event-info",
"url": "http://..."
}]
}
I don't think it's a bug, but not sure why it's not working as expected.
Their code:
onAfterEventsLoad: function(events) {
if(!events) {
return;
}
var list = $('#eventlist');
list.html('');
$.each(events, function(key, val) {
$(document.createElement('li'))
.html('' + val.title + '')
.appendTo(list);
});
},
My code:
'onAfterEventsLoad': function(events) {
if(!events) {
return;
}
var list = $('#eventlist');
list.html('');
$.each(events, function(key, val) {
var d = new Date(val.start_time),
date = weekday[d.getDay()] + ", " + monthNames[d.getMonth()] + " " + d.getDate() + ", " + d.getYear();
$(document.createElement('li'))
.html('<a title="' + date + '" href="' + val.url + '">' + val.title + '</a><br/><small>' + jQuery.timeago(d) + '</small>')
.appendTo(list);
});
},
The url you are trying to load events from is simply returning {"success":1} and not any events for the onAfterEventsLoad handler to iterate through.
This is the cause of your problem, the calendar code is all working fine as far as I can see.

Categories

Resources