Javascript jquery json [duplicate] - javascript

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 6 years ago.
OK, so I have a json structure as follows.
Basically, what I want to do is loop over the json file and pull out the data if Country is equal to a specific value.
I'm sure this is pretty easy but i just can't work it out.
{
"Site ID": 19955,
"Hotels": "Ramada Salzburg City Centre",
"Stadt": "Salzburg",
"Country": "Austria",
"Region": "Central & Eastern Europe",
"Link DE": "",
"Link EN": "",
"Link TR": "",
"Lat": 47.8137521,
"Long": 13.044259,
"Image": "/Salzburg.jpg"
}

Use Array.prototype.filter
let austrianSites = sites.filter(site => site.Country === 'Austria')

Try
for (var i = 0, len = structure.length; i < len; i++) {
if (structure[i].Country === someValue) {
// do something here
}
}

How about checking if the JSON object has a property "Country" and if it does then output it. Hope it helps!
var jsonObject = {
"Site ID": 19955,
"Hotels": "Ramada Salzburg City Centre",
"Stadt": "Salzburg",
"Country": "Austria",
"Region": "Central & Eastern Europe",
"Link DE": "",
"Link EN": "",
"Link TR": "",
"Lat": 47.8137521,
"Long": 13.044259,
"Image": "wp-content/themes/wyndham-hotels/img/Salzburg.jpg"
}
for(var i in jsonObject){
if(jsonObject.hasOwnProperty("Country")){
var x = jsonObject.Country;
}
}
document.write("The Country is: " + x);

Please try this following:
var places = [{
"Site ID": 19955,
"Hotels": "Ramada Salzburg City Centre",
"Stadt": "Salzburg",
"Country": "Austria",
"Region": "Central & Eastern Europe",
"Link DE": "",
"Link EN": "",
"Link TR": "",
"Lat": 47.8137521,
"Long": 13.044259,
"Image": "/Salzburg.jpg"
}, {
"Site ID": 1211,
"Hotels": "test",
"Stadt": "Salzburg",
"Country": "NZ",
"Region": "Central & Eastern Europe",
"Link DE": "",
"Link EN": "",
"Link TR": "",
"Lat": 47.8137521,
"Long": 13.044259,
"Image": "/Salzburg.jpg"
}]
var filtered = places.filter(function(p) {
return p.Country === "NZ";
})
console.log(filtered);

Related

Remove JSON parent element in JavaScript

I'm currently trying to code an application with javascript. It pulls data from a database and the response I'm getting is something like that:
{
"values":[
{
"name": "Munich",
"location": "Germany",
"native_lang": "German",
},
{
"name": "London",
"location": "England",
"native_lang": "English",
},
{
"name": "Rome",
"location": "Italy",
"native_lang": "Italian",
}
]
}
But I need to have the JSON like that:
[
{
"name": "Munich",
"location": "Germany",
"native_lang": "German",
},
{
"name": "London",
"location": "England",
"native_lang": "English",
},
{
"name": "Rome",
"location": "Italy",
"native_lang": "Italian",
}
]
How can I delete the parent values object in my JSON?
SHORT ANSWER:
Just access the values property like a JavaScript object.
LONG ANSWER:
You didn't post the JavaScript code snippet so it's quite difficult to give you an appropriate answer.
Assuming you have the following code:
const jsonString = getDataFromTheDB()
const jsonObject = JSON.parse(jsonObject) // still has the "values" layer
const values = jsonObject.values // what you want, without the "values" layer
// BONUS: Just in case you want to convert the object back to a JSON string but without the "values" layer
const valuesJSON = JSON.stringify(values, undefined, 2)
Based on this post :
just do this (consider json the variable that contains your json):
var key = "values";
var results = json[key];
delete json[key];
json = results;
console.log(json) will output the following:
[
{
"name": "Munich",
"location": "Germany",
"native_lang": "German",
},
{
"name": "London",
"location": "England",
"native_lang": "English",
},
{
"name": "Rome",
"location": "Italy",
"native_lang": "Italian",
}
]
But you dont even have to do the last 2 steps of the code snippet above, you could also just directly use results variable and have the same output by console.log(results).
You could take the object and create a new variable with just the array.
var vals =
{
"values":[
{
"name": "Munich",
"location": "Germany",
"native_lang": "German",
},
{
"name": "London",
"location": "England",
"native_lang": "English",
},
{
"name": "Rome",
"location": "Italy",
"native_lang": "Italian",
}
]
}
var arr = vals.values;
console.log(arr);

unable to access properties of objects inside array of JSON objects [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
{
"results_found": "53",
"results_start": "11",
"results_shown": "10",
"restaurants": [
{
"id": "16774318",
"name": "Otto Enoteca & Pizzeria",
"url": "https://www.zomato.com/new-york-city/otto-enoteca-pizzeria-greenwich-village",
"location": {
"address": "1 5th Avenue, New York, NY 10003",
"locality": "Greenwich Village",
"city": "New York City",
"latitude": "40.732013",
"longitude": "-73.996155",
"zipcode": "10003",
"country_id": "216"
},
"average_cost_for_two": "60",
"price_range": "2",
"currency": "$",
"thumb": "https://b.zmtcdn.com/data/pictures/chains/8/16774318/a54deb9e4dbb79dd7c8091b30c642077_featured_thumb.png",
"featured_image": "https://d.zmtcdn.com/data/pictures/chains/8/16774318/a54deb9e4dbb79dd7c8091b30c642077_featured_v2.png",
"photos_url": "https://www.zomato.com/new-york-city/otto-enoteca-pizzeria-greenwich-village/photos#tabtop",
"menu_url": "https://www.zomato.com/new-york-city/otto-enoteca-pizzeria-greenwich-village/menu#tabtop",
"events_url": "https://www.zomato.com/new-york-city/otto-enoteca-pizzeria-greenwich-village/events#tabtop",
"user_rating": {
"aggregate_rating": "3.7",
"rating_text": "Very Good",
"rating_color": "5BA829",
"votes": "1046"
},
"has_online_delivery": "0",
"is_delivering_now": "0",
"has_table_booking": "0",
"deeplink": "zomato://r/16774318",
"cuisines": "Cafe",
"all_reviews_count": "15",
"photo_count": "18",
"phone_numbers": "(212) 228-2930"
}
]
}
Not able to access property "name" in "restaurants" array in node js.When I am parsing the body using JSON like,
var data = JSON.parse(body);
and trying to print "data"...the result is:
{
"results_found": 0,
"results_start": 0,
"results_shown": 0,
"restaurants": []
}
What may be the reason?? I am confused...the JSON is from Zomato API.
JSON value you have posted is not valid format.. you have a trailing coma after ']'
please use this a valid JSON file
{
"results_found": "53",
"results_start": "11",
"results_shown": "10",
"restaurants": [
{
"id": "16774318",
"name": "Otto Enoteca & Pizzeria",
"url": "https://www.zomato.com/new-york-city/otto-enoteca-pizzeria-greenwich-village",
"location": {
"address": "1 5th Avenue, New York, NY 10003",
"locality": "Greenwich Village",
"city": "New York City",
"latitude": "40.732013",
"longitude": "-73.996155",
"zipcode": "10003",
"country_id": "216"
},
"average_cost_for_two": "60",
"price_range": "2",
"currency": "$",
"thumb": "https://b.zmtcdn.com/data/pictures/chains/8/16774318/a54deb9e4dbb79dd7c8091b30c642077_featured_thumb.png",
"featured_image": "https://d.zmtcdn.com/data/pictures/chains/8/16774318/a54deb9e4dbb79dd7c8091b30c642077_featured_v2.png",
"photos_url": "https://www.zomato.com/new-york-city/otto-enoteca-pizzeria-greenwich-village/photos#tabtop",
"menu_url": "https://www.zomato.com/new-york-city/otto-enoteca-pizzeria-greenwich-village/menu#tabtop",
"events_url": "https://www.zomato.com/new-york-city/otto-enoteca-pizzeria-greenwich-village/events#tabtop",
"user_rating": {
"aggregate_rating": "3.7",
"rating_text": "Very Good",
"rating_color": "5BA829",
"votes": "1046"
},
"has_online_delivery": "0",
"is_delivering_now": "0",
"has_table_booking": "0",
"deeplink": "zomato://r/16774318",
"cuisines": "Cafe",
"all_reviews_count": "15",
"photo_count": "18",
"phone_numbers": "(212) 228-2930",
"photos": [
{
"id": "u_MjA5MjY1OTk5OT",
"url": "https://b.zmtcdn.com/data/reviews_photos/c15/9eb13ceaf6e90129c276ce6ff980bc15_1435111695_640_640_thumb.JPG",
"thumb_url": "https://b.zmtcdn.com/data/reviews_photos/c15/9eb13ceaf6e90129c276ce6ff980bc15_1435111695_200_thumb.JPG",
"user": {
"name": "John Doe",
"zomato_handle": "John",
"foodie_level": "Super Foodie",
"foodie_level_num": "9",
"foodie_color": "f58552",
"profile_url": "https://www.zomato.com/john",
"profile_deeplink": "zoma.to/u/1170245",
"profile_image": "string"
},
"res_id": "16782899",
"caption": "#awesome",
"timestamp": "1435111770",
"friendly_time": "3 months ago",
"width": "640",
"height": "640",
"comments_count": "0",
"likes_count": "0"
}
]
}
]
}
Sample snippet with above JSON
var json = "{\"results_found\":\"53\",\"results_start\":\"11\",\"results_shown\":\"10\",\"restaurants\":[{\"id\":\"16774318\",\"name\":\"Otto Enoteca & Pizzeria\",\"url\":\"https:\/\/www.zomato.com\/new-york-city\/otto-enoteca-pizzeria-greenwich-village\",\"location\":{\"address\":\"1 5th Avenue, New York, NY 10003\",\"locality\":\"Greenwich Village\",\"city\":\"New York City\",\"latitude\":\"40.732013\",\"longitude\":\"-73.996155\",\"zipcode\":\"10003\",\"country_id\":\"216\"},\"average_cost_for_two\":\"60\",\"price_range\":\"2\",\"currency\":\"$\",\"thumb\":\"https:\/\/b.zmtcdn.com\/data\/pictures\/chains\/8\/16774318\/a54deb9e4dbb79dd7c8091b30c642077_featured_thumb.png\",\"featured_image\":\"https:\/\/d.zmtcdn.com\/data\/pictures\/chains\/8\/16774318\/a54deb9e4dbb79dd7c8091b30c642077_featured_v2.png\",\"photos_url\":\"https:\/\/www.zomato.com\/new-york-city\/otto-enoteca-pizzeria-greenwich-village\/photos#tabtop\",\"menu_url\":\"https:\/\/www.zomato.com\/new-york-city\/otto-enoteca-pizzeria-greenwich-village\/menu#tabtop\",\"events_url\":\"https:\/\/www.zomato.com\/new-york-city\/otto-enoteca-pizzeria-greenwich-village\/events#tabtop\",\"user_rating\":{\"aggregate_rating\":\"3.7\",\"rating_text\":\"Very Good\",\"rating_color\":\"5BA829\",\"votes\":\"1046\"},\"has_online_delivery\":\"0\",\"is_delivering_now\":\"0\",\"has_table_booking\":\"0\",\"deeplink\":\"zomato:\/\/r\/16774318\",\"cuisines\":\"Cafe\",\"all_reviews_count\":\"15\",\"photo_count\":\"18\",\"phone_numbers\":\"(212) 228-2930\",\"photos\":[{\"id\":\"u_MjA5MjY1OTk5OT\",\"url\":\"https:\/\/b.zmtcdn.com\/data\/reviews_photos\/c15\/9eb13ceaf6e90129c276ce6ff980bc15_1435111695_640_640_thumb.JPG\",\"thumb_url\":\"https:\/\/b.zmtcdn.com\/data\/reviews_photos\/c15\/9eb13ceaf6e90129c276ce6ff980bc15_1435111695_200_thumb.JPG\",\"user\":{\"name\":\"John Doe\",\"zomato_handle\":\"John\",\"foodie_level\":\"Super Foodie\",\"foodie_level_num\":\"9\",\"foodie_color\":\"f58552\",\"profile_url\":\"https:\/\/www.zomato.com\/john\",\"profile_deeplink\":\"zoma.to\/u\/1170245\",\"profile_image\":\"string\"},\"res_id\":\"16782899\",\"caption\":\"#awesome\",\"timestamp\":\"1435111770\",\"friendly_time\":\"3 months ago\",\"width\":\"640\",\"height\":\"640\",\"comments_count\":\"0\",\"likes_count\":\"0\"}]}]}"
var data = JSON.parse(json);
console.log(data)
Your json is not valid. There is an extra comma at the end of restaurants[0].photos please remove it and everything will work fine

How to do pagination of table data using the received JSON table data in client side without bootstrap?

I have received the table rows data in JSON form using PHP server pages and received the JSON table rows with each new search condition new table is displayed. But the problem is when i have more number of rows so i want to paginate it and also allow user to select the number of rows he want to see like 10, 20, 30.
In short, i want to achieve the following result:
if number of rows are 200 and user want to see to 25 rows at a time then 200/25 means (previous 1->2->3->4.....->8 Next) 8 numbers display at the top of table which allow user to jump to desired page and see rows.
UPDATE: You can check my latest work in this in below answer.
I tried below things in my loadtable.js file as shown below. Also i am attaching both my server side PHP file search.php and client side script loadtable.js which is processing the JSON data and do the pagination task.
//###########################################
// Pagination code start
//###########################################
$("#pagination").attr('style','display:block;');
$("#pagination").html("<p1>Total number of records fetched: "+result.length+"</p1><h5 style='display: inline-block;float:left;width: 150px;'>Number of rows/page: <select id='number-of-records-per-page' onchange='num_of_records(this)' style='width:60px;'><option value='10'>10</option><option value='20'>20</option><option value='30'>30</option><option value='40'>40</option><option value='50'>50</option></select></h5><br><br>");
$("#pagination").append("<div id='nav-pagination' style='float:left;'><a href='#'>«</a><a class='active' href='#'>1</a></div>");
var total_num_of_rows = result.length;
var number_of_rows_per_page = $('#pagination').find('#number-of-records-per-page option:selected').val();
console.log(total_num_of_rows)
console.log(number_of_rows_per_page)
for (i = 1; i < total_num_of_rows/number_of_rows_per_page; i++) {
$("#nav-pagination").append("<a href='#'>"+(i+1)+"</a>");
}
$("#nav-pagination").append("<a href='#'>»</a></div>");
//###########################################
// Pagination code end
//###########################################
The problem is i am doing pagination inside ajax success funtion success:function(data){ which i think will be called once when the JSON result is received from the Server side. Also as i m beginner in ajax feeling difficulty to proceed. Please help.
Complete code of client side script loadtable.js
// This is script to load table based on filter section
$(document).ready(function() {
var delay = 1000;
// Campaign Submit Info
$('[name="search_submit"]').click(function(e) {
$('#load-csv-file-button').attr('style','display:none;');
$("#filterRecords").attr('style','display:block;');
$('#add_lead_info').attr('style','display:none;');
e.preventDefault();
var lead_owner = $('#filterformpost').find('#lead_owner_select option:selected').val();
var lead_status = $('#filterformpost').find('#lead_status_select option:selected').val();
var campaign_status = $('#filterformpost').find('#campaign_status_select option:selected').val();
var company_name = $('#filterformpost').find('#company_name_select option:selected').val();
var tech_area = $('#filterformpost').find('#tech_area_select option:selected').val();
var firm_size = $('#filterformpost').find('#firm_size_select option:selected').val();
var firm_type = $('#filterformpost').find('#firm_type_select option:selected').val();
var country_name = $('#filterformpost').find('#country_name_select option:selected').val();
var state_name = $('#filterformpost').find('#state_name_select option:selected').val();
var start_date = $('#filterformpost').find('#start_date_search').val();
var end_date = $('#filterformpost').find('#end_date_search').val();
$.ajax({
type: "POST",
url: "./server/search.php",
data: {
"lead_owner": lead_owner,
"lead_status": lead_status,
"campaign_status": campaign_status,
"company_name": company_name,
"tech_area": tech_area,
"firm_size": firm_size,
"firm_type": firm_type,
"country_name": country_name,
"state_name": state_name,
"start_date": start_date,
"end_date": end_date
},
beforeSend: function() {
$('.search_lead_filter_message_box').html(
'<img src="tenor.gif" width="40" height="40"/>'
);
},
success:function(data){
var result = $.parseJSON(data);
$("#filterRecords").empty();
//###########################################
// Pagination code start
//###########################################
$("#pagination").attr('style','display:block;');
$("#pagination").html("<p1>Total number of records fetched: "+result.length+"</p1><h5 style='display: inline-block;float:left;width: 150px;'>Number of rows/page: <select id='number-of-records-per-page' onchange='num_of_records(this)' style='width:60px;'><option value='10'>10</option><option value='20'>20</option><option value='30'>30</option><option value='40'>40</option><option value='50'>50</option></select></h5><br><br>");
$("#pagination").append("<div id='nav-pagination' style='float:left;'><a href='#'>«</a><a class='active' href='#'>1</a></div>");
var total_num_of_rows = result.length;
var number_of_rows_per_page = $('#pagination').find('#number-of-records-per-page option:selected').val();
console.log(total_num_of_rows)
console.log(number_of_rows_per_page)
for (i = 1; i < total_num_of_rows/number_of_rows_per_page; i++) {
$("#nav-pagination").append("<a href='#'>"+(i+1)+"</a>");
}
$("#nav-pagination").append("<a href='#'>»</a></div>");
//###########################################
// Pagination code end
//###########################################
var table='';
table = $("<table></table>");
table.append('<thead><th>#</th><th>Lead Name</th><th>Company</th><th>Email</th><th>Phone</th><th>Lead Owner</th></thead>');
table.append('<tbody></tbody>');
var i = 1;
$.each(result, function(key, value) {
table.last().append("<tr><td>" + i + "</td><td><a target='_blank' href=./lead/index.html?lead_id="+ value['Lead_Id'] + " </a>" + value['FirstName'] + ' ' + value['LastName'] + "</td><td>" + value['Company'] + "</td><td>" + value['Email'] + "</td><td>" + value['Phone'] + "</td><td><a target='_blank' href=./account/index.html?user_id="+ value['LeadAddedBy'] + " </a>" + value['LeadAddedBy'] + "</td></tr>" );
i = i + 1;
});
table.after().append("<br><br>");
$("#filterRecords").html(table);
$('.search_lead_filter_message_box').html('');
}
});
});
});
I tried and done paginated in JSFiddle (https://jsfiddle.net/rinku16/hn3t9gz6/33/) using the JSON Data but the problem is now that it is not correctly working for the display of number of rows per page.
I made a separate function to process the JSON data and display the result.
But i am facing little issues as below:
1) Number of rows per page is not working properly, although i tried to change the value of var elements_per_page = 3;. I also want to select the user select option to see number of rows per page he want to see. as you can see below pic.
2) Also overflow-x style is not working properly as shown in below pic.
3) Also i want to use CSS focus property to know which page the user is class=nav of 1,2,3,4 button between previous and next.
JSON data at client side to paginate.
var 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": "28",
"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
},
{
"Lead_Id": "122",
"FirstName": "Test1",
"LastName": "User1",
"Company": "NA",
"Website": "NA",
"Designation": "Tester",
"Linkedin": "NA",
"Email": "test1#test.com",
"Phone": "7508023064",
"State": "Chandigarh",
"Country": "India",
"TechArea": "Computers",
"FirmType": "Corporate",
"FirmSize": "Less than 10",
"LastContactDate": "2020-03-05",
"NextContactDate": "2020-03-05",
"LeadDescription": "Testing Lead Description",
"OwnerNotes": "Testing Owner Notes",
"SetReminder": "2020-03-05",
"AdminNotes": "This is testing admin notes",
"LeadStatus": "Planned",
"LeadAddedBy": "18",
"LeadAddedOn": "2020-03-05 17:34:25",
"LeadUpdatedBy": null,
"LeadUpdatedOn": null
},
{
"Lead_Id": "123",
"FirstName": "Test2",
"LastName": "User2",
"Company": "NA",
"Website": "NA",
"Designation": "Tester",
"Linkedin": "NA",
"Email": "test2#test.com",
"Phone": "7508023064",
"State": "Chandigarh",
"Country": "India",
"TechArea": "Computers",
"FirmType": "Corporate",
"FirmSize": "Less than 10",
"LastContactDate": "2020-03-05",
"NextContactDate": "2020-03-05",
"LeadDescription": "Testing Lead Description",
"OwnerNotes": "Testing Owner Notes",
"SetReminder": "2020-03-05",
"AdminNotes": "This is testing admin notes",
"LeadStatus": "Planned",
"LeadAddedBy": "18",
"LeadAddedOn": "2020-03-05 17:34:25",
"LeadUpdatedBy": null,
"LeadUpdatedOn": null
},
{
"Lead_Id": "124",
"FirstName": "Test3",
"LastName": "",
"Company": "NA",
"Website": "NA",
"Designation": "Tester",
"Linkedin": "NA",
"Email": "test3#test.com",
"Phone": "7508023064",
"State": "Chandigarh",
"Country": "India",
"TechArea": "Computers",
"FirmType": "Corporate",
"FirmSize": "Less than 10",
"LastContactDate": "2020-03-05",
"NextContactDate": "2020-03-05",
"LeadDescription": "Testing Lead Description",
"OwnerNotes": "Testing Owner Notes",
"SetReminder": "2020-03-05",
"AdminNotes": "",
"LeadStatus": "Planned",
"LeadAddedBy": "18",
"LeadAddedOn": "2020-03-06 10:54:12",
"LeadUpdatedBy": null,
"LeadUpdatedOn": null
},
{
"Lead_Id": "125",
"FirstName": "Test4",
"LastName": "User4",
"Company": "",
"Website": "NA",
"Designation": "",
"Linkedin": "NA",
"Email": "test4#test.com",
"Phone": "7508023064",
"State": "Chandigarh",
"Country": "India",
"TechArea": "Computers",
"FirmType": "Corporate",
"FirmSize": "Less than 10",
"LastContactDate": "2020-03-05",
"NextContactDate": "2020-03-05",
"LeadDescription": "Testing Lead Description",
"OwnerNotes": "",
"SetReminder": "2020-03-05",
"AdminNotes": "This is testing admin notes",
"LeadStatus": "",
"LeadAddedBy": "18",
"LeadAddedOn": "2020-03-06 10:54:12",
"LeadUpdatedBy": null,
"LeadUpdatedOn": null
},
{
"Lead_Id": "126",
"FirstName": "Test5",
"LastName": "",
"Company": "NA",
"Website": "NA",
"Designation": "Tester",
"Linkedin": "NA",
"Email": "test5#test.com",
"Phone": "7508023064",
"State": "Chandigarh",
"Country": "India",
"TechArea": "Computers",
"FirmType": "Corporate",
"FirmSize": "Less than 10",
"LastContactDate": "2020-03-05",
"NextContactDate": "2020-03-05",
"LeadDescription": "This is test description",
"OwnerNotes": "Testing Owner Notes",
"SetReminder": "2020-03-05",
"AdminNotes": "This is testing admin notes",
"LeadStatus": "Planned",
"LeadAddedBy": "18",
"LeadAddedOn": "2020-03-06 10:54:12",
"LeadUpdatedBy": "18",
"LeadUpdatedOn": "2020-03-06 10:55:08"
},
{
"Lead_Id": "127",
"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": "28",
"LeadAddedOn": "2020-02-03 16:28:26",
"LeadUpdatedBy": null,
"LeadUpdatedOn": null
}
];
Below is latest script at client side.
// This is script to load table based on filter section
$(document).ready(function() {
var delay = 1000;
// Campaign Submit Info
$('[name="search_submit"]').click(function(e) {
$('#load-csv-file-button').attr('style','display:none;');
$("#filterRecords").attr('style','display:block;');
$('#add_lead_info').attr('style','display:none;');
e.preventDefault();
var lead_owner = $('#filterformpost').find('#lead_owner_select option:selected').val();
var lead_status = $('#filterformpost').find('#lead_status_select option:selected').val();
var campaign_status = $('#filterformpost').find('#campaign_status_select option:selected').val();
var company_name = $('#filterformpost').find('#company_name_select option:selected').val();
var tech_area = $('#filterformpost').find('#tech_area_select option:selected').val();
var firm_size = $('#filterformpost').find('#firm_size_select option:selected').val();
var firm_type = $('#filterformpost').find('#firm_type_select option:selected').val();
var country_name = $('#filterformpost').find('#country_name_select option:selected').val();
var state_name = $('#filterformpost').find('#state_name_select option:selected').val();
var start_date = $('#filterformpost').find('#start_date_search').val();
var end_date = $('#filterformpost').find('#end_date_search').val();
$.ajax({
type: "POST",
url: "./server/search.php",
data: {
"lead_owner": lead_owner,
"lead_status": lead_status,
"campaign_status": campaign_status,
"company_name": company_name,
"tech_area": tech_area,
"firm_size": firm_size,
"firm_type": firm_type,
"country_name": country_name,
"state_name": state_name,
"start_date": start_date,
"end_date": end_date
},
beforeSend: function() {
$('.search_lead_filter_message_box').html(
'<img src="tenor.gif" width="40" height="40"/>'
);
},
success:function(data){
console.log('data:')
console.log(data)
userDetails = data
var result = $.parseJSON(data);
console.log('result:')
console.log(result)
$("#filterRecords").empty();
//###########################################
// Pagination code start
//###########################################
$("#pagination").attr('style','display:block;');
$('#pagination').html('<div class="row"><div class="col"><button class="col" 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" id="nextValue">Next <i class="ion-skip-forward"></i></button></div></div>');
paginate_json_data(result)
//###########################################
// Pagination code end
//###########################################
$('.search_lead_filter_message_box').html('');
}
});
});
});
function paginate_json_data(userDetails){
$('.search_lead_filter_message_box').html('');
userDetails = userDetails
// var table = $('#myTable');
var table='';
table = $("<table id='myTable' style='width:30%;'></table>");
var max_size=userDetails.length;
var sta = 0;
//here if i change 3 to 10 then number of rows some navigation 3 rows display and then 10 row is displayed.
var elements_per_page = 3;
var limit = elements_per_page;
goFun(sta,limit);
function goFun(sta,limit){
console.log(sta,limit);
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 style="overflow-x:auto;"></tbody>');
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)
}
$("#filterRecords").html(table);
}
$('#nextValue').click(function(){
var next = limit;
if(max_size>=next) {
def = limit+elements_per_page;
limit = def
table.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;
table.empty();
goFun(pre,limit);
}
});
var number = Math.round(userDetails.length / elements_per_page);
for(i=0;i<=number;i++) {
$('.nav').append('<button class="btn">'+i+'</button>');
}
$('.nav button').click(function(){
var start = $(this).text();
table.empty();
limit = 3*(parseInt(start)+1) > max_size ? max_size: 3*(parseInt(start)+1)
goFun(start*3,limit);
});
}

Query JSON data sharing same value

Sample JSON Data:
{
"results": [
{
"name": "John Smith",
"state": "NY",
"phone": "555-555-1111"
},
{
"name": "Mary Jones",
"state": "PA",
"phone": "555-555-2222"
},
{
"name": "Edward Edwards",
"state": "NY",
"phone": "555-555-3333"
},
{
"name": "Abby Abberson",
"state": "RI",
"phone": "555-555-4444"
},
]}
With this sample data I can display individual values from the results [] array with object.name and object.phone to look something like:
John Smith 555-555-1111<br />
Mary Jones 555-555-2222<br />
Edward Edwards 555-555-3333<br />
Abby Abberson 555-555-4444
What I am trying to do now is select just the people who's state value is NY and only display their object.name and object.phone:
John Smith 555-555-1111<br />
Edward Edwards 555-555-3333
I tried this lovely little block but all it did was print all the names, which makes sense after I tried it.
if (object.state = "NY") {
div.append(repName);
}
I can't seem to think of a way to only display those that share a the same state.
I'm probably searching for the wrong terms or have to go about this another way... please help!
You are using =(assignment operator),which is wrong.
You have to use ==(comparison operator)
So do like below:-
if (object.state == "NY") {
div.append(repName);
}
Working sample-
var obj = {
"results": [
{
"name": "John Smith",
"state": "NY",
"phone": "555-555-1111"
},
{
"name": "Mary Jones",
"state": "PA",
"phone": "555-555-2222"
},
{
"name": "Edward Edwards",
"state": "NY",
"phone": "555-555-3333"
},
{
"name": "Abby Abberson",
"state": "RI",
"phone": "555-555-4444"
},
]};
$(obj.results).each(function(k,object){
if (object.state == "NY") {
$('#final_data').append(object.name +" : "+object.phone+"<br/>");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="final_data"></div>
My one cent solution:
var obj = {
"results": [
{
"name": "John Smith",
"state": "NY",
"phone": "555-555-1111"
},
{
"name": "Mary Jones",
"state": "PA",
"phone": "555-555-2222"
},
{
"name": "Edward Edwards",
"state": "NY",
"phone": "555-555-3333"
},
{
"name": "Abby Abberson",
"state": "RI",
"phone": "555-555-4444"
},
]};
obj.results.forEach((value) => {
if (value.state === "NY") {
const li = document.createElement("li");
li.innerHTML = `${value.name} : ${value.phone}`;
document.querySelector("#final_data").appendChild(li);
}
});
<ul id="final_data"></ul>
Like Alive said you used the assignment operator = instead of comparison operator === or ==.

Accessing objects in arrays inside objects in Angular

I am having quite a hard time accessing data from an api call and having it shown on Mapbox. I am able to have one marker shown on the map, while I should have 10 markers. I think I am doing something wrong with ng-repeat, but I am not sure what. Any help would be appreciated.
Here is a link to view the full JSON response from the API call http://jsonblob.com/55e734cee4b01190df374f1e
// index.html
<div ng-repeat="venue in bars.venues">
<marker lat="{{venue.location.lat}}" lng="{{venue.location.lng}}">
<h1>{{venue.name}}</h1>
<p>{{venue.contact}}</p>
<p>{{venue.location.formattedAddress}}</p>
</marker>
</div>
// app.js
$http.get(url)
.then(function (response) {
$scope.bars = response.data.response;
});
// sample data from api
{
"meta": {
"code": 200,
"requestId": "55e72707498e3d9a002d7bc4"
},
"response": {
"venues": [
{
"id": "42c1e480f964a520c4251fe3",
"name": "The View",
"contact": {
"phone": "4158961600",
"formattedPhone": "(415) 896-1600"
},
"location": {
"address": "55 4th St",
"crossStreet": "at Marriott Marquis",
"lat": 37.78510950100554,
"lng": -122.40469515323639,
"distance": 29,
"postalCode": "94103",
"cc": "US",
"city": "San Francisco",
"state": "CA",
"country": "United States",
"formattedAddress": [
"55 4th St (at Marriott Marquis)",
"San Francisco, CA 94103",
"United States"
]
},
"categories": [
{
"id": "4bf58dd8d48988d1d5941735",
"name": "Hotel Bar",
"pluralName": "Hotel Bars",
"shortName": "Hotel Bar",
"icon": {
"prefix": "https://ss3.4sqi.net/img/categories_v2/travel/hotel_bar_",
"suffix": ".png"
},
"primary": true
}
],
"verified": false,
"stats": {
"checkinsCount": 12634,
"usersCount": 9499,
"tipCount": 121
},
"url": "http://www.sfviewlounge.com",
"hasMenu": true,
"menu": {
"type": "Menu",
"label": "Menu",
"anchor": "View Menu",
"url": "https://foursquare.com/v/the-view/42c1e480f964a520c4251fe3/menu",
"mobileUrl": "https://foursquare.com/v/42c1e480f964a520c4251fe3/device_menu"
},
So I figured out why only one marker was showing. I was previously using angular google maps and had ngMaps as a module. After I deleted it, all my markers showed.

Categories