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

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

Related

How to paginate the JSON data at client side without using Bootstrap?

Solution is in this JSFiddle: https://jsfiddle.net/rinku16/mpo7xyjk/17/
When the user click on Filter Search and JSON is downloaded on client side according to the search condition and my pagination JS function partition the rows according to number of rows per page and accordingly make numeral navigation button between previous and next buttons.
I have problem of synchronization of navigation button for pages and previous/Next Button.
My Problem as follows
For example: Initially on search click it displays only table header but if user presses next button it displays (10-19) 10 records continuing (skipped) after 0-9 of previous rows but if user click 0 navigation button (between previous and next buttons) but it displays (0-1-2) 3 rows (but it should display 0-9 rows) and when click on 1 button it should display (10-19) but it displaying (3-4-5).
I have updated the code in this JSFiddle link (https://jsfiddle.net/rinku16/hn3t9gz6/33/) but it is not working properly.
I am trying to build a logic. You can check all logic at the link. I am not able to do following task.
HTML:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
<div class="row">
<div class="col">
<div>
Pagination Div
<div id="pagination"></div>
</div>
</div>
</div>
<div class="row" style="overflow-x:auto;">
<div class="col">
<div>
Records Div
<div id="filterRecords"></div>
</div>
</div>
</div>
</body>
</html>
Logic for client side:
// This is script to load table based on filter section
$(document).ready(function() {
userDetails = [{
"Lead_Id": "66",
"FirstName": "John",
"LastName": "Doe",
"Company": "Google",
"Website": "www.google.com",
"Designation": "Manager",
"Linkedin": "www.linkedin.com\/john-doe",
"Email": "johndoe#google.com",
"Phone": "5125501553",
"State": "Delaware",
"Country": "USA",
"TechArea": "Cloud computing",
"FirmType": "Corporate",
"FirmSize": "Less than 10",
"LastContactDate": "2020-02-03",
"NextContactDate": "2020-02-29",
"LeadDescription": "This is lead description testing",
"OwnerNotes": null,
"SetReminder": "2020-02-29",
"AdminNotes": "This is admin notes testing",
"LeadStatus": "Planned",
"LeadAddedBy": "18",
"LeadAddedOn": "2020-02-03 16:28:26",
"LeadUpdatedBy": null,
"LeadUpdatedOn": null
}, {
"Lead_Id": "67",
"FirstName": "Tohn",
"LastName": "Doe",
"Company": "Microsoft",
"Website": "www.microsoft.com",
"Designation": "Manager",
"Linkedin": "www.linkedin.com\/tohn-doe",
"Email": "tohn#microsoft.com",
"Phone": "123456",
"State": "California",
"Country": "USA",
"TechArea": "Computer Networks",
"FirmType": "Corporate",
"FirmSize": "Less than 10",
"LastContactDate": "2020-03-05",
"NextContactDate": "2020-03-07",
"LeadDescription": "This is test lead description",
"OwnerNotes": null,
"SetReminder": "2020-03-11",
"AdminNotes": "This is testing admin notes",
"LeadStatus": "Planned",
"LeadAddedBy": "18",
"LeadAddedOn": "2020-03-05 10:47:21",
"LeadUpdatedBy": null,
"LeadUpdatedOn": null
}];
//More JSON object you can get on jsfiddle link
$("#filterRecords").empty();
var result = $.parseJSON(userDetails);
//###########################################
// Pagination code start
//###########################################
$("#pagination").attr('style', 'display:block;');
$('#pagination').html('<div class="row"><div class="col"><button class="col PreviousButton" id="PreValue"><i class="ion-skip-backward"></i> Previous</button></div> <div id="nav-numbers" class="col nav"></div> <div class="col"><button class="col NextButton" id="nextValue">Next <i class="ion-skip-forward"></i></button></div></div>');
paginate_json_data(result)
$("#filterRecords").html(table);
//###########################################
// Pagination code end
//###########################################
});
function paginate_json_data(userDetails) {
var table = '';
table = $("<table></table>");
table.append('<thead><th>#</th><th>Name</th><th>Company</th><th>Website</th><th>Designation</th><th>Linkedin</th><th>Email</th><th>Phone</th><th>State</th><th>Country</th><th>TechArea</th><th>Firm Type</th><th>Firm Size</th><th>Last Contact Date</th><th>Next Contact Date</th><th>Lead Description</th><th>Owner Notes</th><th>Reminder Date</th><th>Admin Notes</th><th>Lead Status</th><th>Lead Added By</th><th>Lead Added On</th><th>Lead Updated By</th><th>Lead Updated On</th></thead><br>');
table.append('<tbody id="myTable"></tbody>');
userDetails = userDetails
$('#pagination').append('<p1>Total number of rows fetched: ' + userDetails.length + '</p1>');
var max_size = userDetails.length;
var sta = 0;
var elements_per_page = 10;
// var elements_per_page = rows_per_page;
var limit = elements_per_page;
goFun(sta, limit);
function goFun(sta, limit) {
// console.log(sta,limit);
for (var i = sta; i < limit; i++) {
var tab = '<tr><td>' + i + "\n" + '</td><td>' + "<a target='_blank' href=./lead/index.html?lead_id=" + userDetails[i].Lead_Id + " </a>" + userDetails[i].FirstName + ' ' + userDetails[i].LastName + "\n" + '</td><td>' + userDetails[i].Company + "\n" + '</td><td>' + userDetails[i].Website + "\n" + '</td><td>' + userDetails[i].Designation + "\n" + '</td><td>' + userDetails[i].Linkedin + "\n" + '</td><td>' + "" + userDetails[i].Email + "" + "\n" + '</td><td>' + userDetails[i].Phone + "\n" + '</td><td>' + userDetails[i].State + "\n" + '</td><td>' + userDetails[i].Country + "\n" + '</td><td>' + userDetails[i].TechArea + "\n" + '</td><td>' + userDetails[i].FirmType + "\n" + '</td><td>' + userDetails[i].FirmSize + "\n" + '</td><td>' + userDetails[i].LastContactDate + "\n" + '</td><td>' + userDetails[i].NextContactDate + "\n" + '</td><td>' + userDetails[i].LeadDescription + "\n" + '</td><td>' + userDetails[i].OwnerNotes + "\n" + '</td><td>' + userDetails[i].SetReminder + "\n" + '</td><td>' + userDetails[i].AdminNotes + "\n" + '</td><td>' + userDetails[i].LeadStatus + "\n" + '</td><td>' + "<a target='_blank' href=./account/index.html?user_id=" + userDetails[i].LeadAddedBy + " </a>" + userDetails[i].LeadAddedBy + "\n" + '</td><td>' + userDetails[i].LeadAddedOn + "\n" + '</td><td>' + userDetails[i].LeadUpdatedBy + "\n" + '</td><td>' + userDetails[i].LeadUpdatedOn + "\n" + '</td></tr>';
$('#myTable').append(tab)
}
}
$('#nextValue').click(function() {
var next = limit;
if (max_size >= next) {
def = limit + elements_per_page;
limit = def
$('#myTable').empty();
if (limit > max_size) {
def = max_size;
}
goFun(next, def);
}
});
$('#PreValue').click(function() {
var pre = limit - (2 * elements_per_page);
if (pre >= 0) {
limit = limit - elements_per_page;
$('#myTable').empty();
goFun(pre, limit);
}
});
var number = Math.round(userDetails.length / elements_per_page);
for (i = 0; i <= number; i++) {
$('.nav').append('<button class="nav-numbers btn" id=' + i + '>' + i + '</button>');
}
$('.nav button').click(function() {
var start = $(this).text();
$('#myTable').empty();
limit = 3 * (parseInt(start) + 1) > max_size ? max_size : 3 * (parseInt(start) + 1)
goFun(start * 3, limit);
});
}
I want to do two things using paginate.
Partition the number of rows example: JSON has 32 rows then rows view per page 10 then i have buttons as 1 (10 row), [2] (10 rows),[3] (10 rows), [4] (2 rows) {I have written code for this in link}
Move the focus from one button to next button on (next button click) 1 -> [2] -> [3] -> [4]) {I have not written code for this as it need CSS changes using button id(1->[2]->[3]->[4])}
The problem is button click previous and next are not synchronized with focused buttons (1->[2]->[3]->[4]).
Screenshot of my work until now.
Please correct my code.
If understand it right, if you click the button 1,2 or 3 it shows only the next 3 new but should show the next 10 new.
then change the following:
change the "3" to "10" in your code
$('.nav button').click(function() {
var start = $(this).text();
$('#myTable').empty();
limit = 10 * (parseInt(start) + 1) > max_size ? max_size : 10 * (parseInt(start) + 1)
goFun(start * 10, limit);
});
EDIT:
to start directly with result, you can execute the first button like
$('.nav button')[0].click()
only put this at the end of your code
see fiddle
Take a look on that fork (https://jsfiddle.net/Kyrylo/2hbxmove/)
Instead focus I use button's disable/enable, but idea the same.
// keep in scope var current - ref to current page
// on nav btn click, prev, next
// remove disabled attr from current btn
$('#' + current).removeAttr('disabled');
// update current value, line below from onPrevClick handler
current = Math.max(current - 1 , 0);
// disable new current
$('#' + current).attr('disabled', 'disabled');

Get value from nested array (json)

Im trying to get value from an array:
[
{
"id": "5899aaa321e01b8b050041cb",
"name": "John Doe",
"picture": {"small": "https://cdn.image.com/1234"},
"age": 28,
"location": {"city": "London"},
"following": 1,
"resources": {"band": "http://image/music"},
"top_works": [
{
"points": 20,
"portfolio": {
"facebook_id": "1e691681472",
"picture": {"small": "https://cdn.image.com/1234"}
}
},
{
"points": 10,
"portfolio": {
"facebook_id": "1e6916r17ry",
"picture": {"small": "https://cdn.image.com/1234"}
}
}
]
}
]
$(document).ready(function() {
$.ajax({
type: 'GET',
url: '/api/url/123',
data: { get_param: 'value' },
dataType: 'json',
success: function (data) {
$.each(data, function (index, element) {
$('#api').append('<div>'
+ ' <div><h3>' + element.name + '</h3></div>'
+ '<div>' + element.top_works[2].portfolio.picture.small + '></div>');
});
}
});
});
I can read without problem all, neither the "top_works, because i need to specific the number [x], and I need a loop.
In some case if the top_works is empty i get an "undefined in console", i need to show a white space if the element does'nt exsist.
Someone can help me?
You should verify if that exists, something like:
$.each(data, function (index, element) {
var HTML = '<div>'
+ ' <div><h3>' + element.name + '</h3></div>';
var exists = element.top_works[2] && element.top_works[2].portfolio && element.top_works[2].portfolio.picture && element.top_works[2].portfolio.picture.small;
HTML+= exists ? '<div>' + element.top_works[2].portfolio.picture.small + '</div>' : '<div>#empty space</div>';
$('#api').append(HTML + '</div>');
});
But if you want to search for a picture on the last index, maybe you can do this:
$.each(data, function (index, element) {
var HTML = '<div>'
+ ' <div><h3>' + element.name + '</h3></div>';
var last = element.top_works ? element.top_works.length-1 : -1;
var exists = last >= 0;
HTML+= exists ? '<div>' + element.top_works[last].portfolio.picture.small + '</div>' : '<div>#empty space</div>';
$('#api').append(HTML + '</div>');
});
EDIT
For a loop, you can do this:
$.each(data, function (index, element) {
var HTML = '<div>'
+ ' <div><h3>' + element.name + '</h3></div>';
if(element.top_works && element.top_works.length > 0) {
for(var i in element.top_works) {
HTML+= '<div>' + element.top_works[i].portfolio.picture.small + '</div>';
}
} else {
HTML += '<div>#empty space</div>';
}
$('#api').append(HTML + '</div>');
});
you can make use of array.length property to check if and element exists or not as shown in following example.
var topWorks = { "top_works": [
{
"points": 20,
"portfolio": {
"facebook_id": "1e691681472",
"picture": {
"small": "https://cdn.image.com/1234",
}
}
},
{
"points": 10,
"portfolio": {
"facebook_id": "1e6916r17ry",
"picture": {
"small": "https://cdn.image.com/1234",
}
}
},
]
}
if(topWorks.top_works.length > 0) {
console.log("Top works has element at index 0");
}
if(topWorks.top_works.length > 1) {
console.log("Top works has element at index 1");
}
if(topWorks.top_works.length > 2) {
console.log("Top works has element at index 2");
}else
{
console.log("Top works does not have element at index 2");
}

Javascript forEach is not working for json

I have a ajax returning data some times like
{
"results": [{
"symbol": "AppConomy",
"Name": null,
"PriceSales": null
}]
}
for above my forEach function is working fine but when same data is returning
{
"results": {
"symbol": "AppConomy",
"Name": null,
"PriceSales": null
}
}
my forEach function not working
$.get(url, function(data){
var x =data['results'];
x.forEach(function logArrayElements(element, index, array) {
$(self).append('<button class="tag-format" title="'+array[index].Name+'" style="color:#fff;background-color:rgb(0,151,216);border:1px solid;border-radius:10px;"> '+ array[index].symbol +" - "+ array[index].PriceSales +' </button>');
});
});
That's because your JSON isn't an array. You can easily check beforehand using Array.isArray(). You should also be using getJSON if the data you are retrieving is in fact JSON.
$.getJSON(url, function(data) {
var x = data.results;
if(Array.isArray(x)) {
x.forEach(function logArrayElements(element, index, array) {
$(self).append('<button class="tag-format" title="' + array[index].Name + '" style="color:#fff;background-color:rgb(0,151,216);border:1px solid;border-radius:10px;"> ' + array[index].symbol + " - " + array[index].PriceSales + ' </button>');
});
} else {
$(self).append('<button class="tag-format" title="' + x.Name + '" style="color:#fff;background-color:rgb(0,151,216);border:1px solid;border-radius:10px;"> ' + x.symbol + " - " + x.PriceSales + ' </button>');
}
});
Your forEach is for iterating over an array. In your second JSON, there is no array to iterate over, so you need to call the function directly on data['results']:
$.get(url, function(data){
var x = data['results'],
addButton = function(item) {
$(self).append('<button class="tag-format" title="'+array[index].Name+'" style="color:#fff;background-color:rgb(0,151,216);border:1px solid;border-radius:10px;"> '+ array[index].symbol +" - "+ array[index].PriceSales +' </button>');
};
if(Array.isArray(x)) {
x.forEach(function logArrayElements(element, index, array) {
addButton(array[index]);
});
} else {
addButton(x);
}
});
Javascript object is not an Array.
Html
<div id="results"></div>
Javascript
var firstArray = {
"results": [{
"symbol": "AppConomy",
"Name": null,
"PriceSales": null
}]};
var secondArray = {
"results": {
"symbol": "AppConomy",
"Name": null,
"PriceSales": null
}};
//Result: 1
$("#results").append("<span>FirstArray result: " + firstArray['results'].length + "</span><br/>");
//Result: undefined
$("#results").append("<span>FirstArray result: " + secondArray['results'].length + "</span><br/>");

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.

JSON Loop through nested array

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>'
);

Categories

Resources