Iterate through JSON from MapQuest API - javascript

I'm parsing JSON response from the MapQuest API. I need all of the 'narratives' from the 'legs' node under 'maneuvers' (legs-> maneuvers -> get all narratives), but I cannot figure it out.
I can get most of the values like so:
$(function(){
var mq = jQuery.parseJSON(jsonResponse);
$("#fuel").html(mq.renderMatrixResults[0].route.fuelUsed);
$("#rtime").html(mq.renderMatrixResults[0].route.realTime);
});
Part of JSON response:
{
"renderMatrixResults": [
{
"route": {
"hasTollRoad": true,
"computedWaypoints": [
],
"fuelUsed": 2.24,
"hasUnpaved": false,
"hasHighway": true,
"realTime": 5556,
"boundingBox": {
"ul": {
"lng": -74.240074,
"lat": 40.662548
},
"lr": {
"lng": -74.132072,
"lat": 40.573451
}
},
"distance": 38.998,
"time": 5523,
"hasSeasonalClosure": false,
"locations": [
{
"latLng": {
"lng": -74.18862,
"lat": 40.609712
},
"adminArea4": "Brooklyn",
"adminArea5Type": "City",
"adminArea4Type": "County",
"adminArea5": "Brooklyn",
"street": "1234 Test Lane",
"adminArea1": "US",
"adminArea3": "NY",
"type": "s",
"displayLatLng": {
"lng": -74.188621,
"lat": 40.60971
},
"linkId": 33589148,
"postalCode": "10001-6992",
"sideOfStreet": "L",
"dragPoint": false,
"adminArea1Type": "Country",
"geocodeQuality": "POINT",
"geocodeQualityCode": "P1AAA",
"adminArea3Type": "State"
},
{
"latLng": {
"lng": -74.194858,
"lat": 40.601623
},
"adminArea4": "Brooklyn",
"adminArea5Type": "City",
"adminArea4Type": "County",
"adminArea5": "Brooklyn",
"street": "5678 Example Street",
"adminArea1": "US",
"adminArea3": "NY",
"type": "s",
"displayLatLng": {
"lng": -74.194854,
"lat": 40.601623
},
"linkId": 33361764,
"postalCode": "10001-5483",
"sideOfStreet": "R",
"dragPoint": false,
"adminArea1Type": "Country",
"geocodeQuality": "POINT",
"geocodeQualityCode": "P1AAA",
"adminArea3Type": "State"
}
],
"hasCountryCross": false,
"legs": [
{
"hasTollRoad": false,
"index": 0,
"roadGradeStrategy": [
[
]
],
"hasHighway": false,
"hasUnpaved": false,
"distance": 0.882,
"time": 145,
"origIndex": 1,
"hasSeasonalClosure": false,
"origNarrative": "Go west on some road",
"hasCountryCross": false,
"formattedTime": "00:02:25",
"destNarrative": "Proceed to 789 GIRAFFE STREET",
"destIndex": 1,
"maneuvers": [
{
"signs": [
],
"index": 0,
"maneuverNotes": [
],
"direction": 4,
"narrative": "Start out going south on Elephant Avenue.",
"iconUrl": "https://content.mapquest.com/mqsite/turnsigns/icon-dirs-start_sm.gif",
"distance": 0.57,
"time": 79,
"linkIds": [
],
"streets": [
"Elephant Avenue"
],
"attributes": 0,
"transportMode": "AUTO",
"formattedTime": "00:01:19",
"directionName": "South",
"mapUrl": "https://www.mapquestapi.com/staticmap/v4/getmap?key=Fmjtd|luur20uanq,b0=o5-9ayxdw&type=map&size=225,160&pois=purple-1,40.60971,-74.188621,0,0|purple-2,40.602351999999996,-74.189582,0,0|�er=40.606031,-74.18910149999999&zoom=10&rand=-1416511403&session=53c1fb45-030d-0004-02b7-16b5-00163e4c0d3f",
"startPoint": {
"lng": -74.188621,
"lat": 40.60971
},
"turnType": 2
},
{
"signs": [
],
"index": 1,
"maneuverNotes": [
],
"direction": 7,
"narrative": "Turn right onto Tiger Blvd.",
"iconUrl": "https://content.mapquest.com/mqsite/turnsigns/rs_right_sm.gif",
"distance": 0.269,
"time": 56,
"linkIds": [
],
"streets": [
"Tiger Blvd"
],
"attributes": 0,
"transportMode": "AUTO",
"formattedTime": "00:00:56",
"directionName": "West",
"mapUrl": "https://www.mapquestapi.com/staticmap/v4/getmap?key=Fmjtd|luur20uanq,b0=o5-9ayxdw&type=map&size=225,160&pois=purple-2,40.602351999999996,-74.189582,0,0|purple-3,40.601127,-74.194366,0,0|�er=40.601739499999994,-74.191974&zoom=12&rand=-1416511403&session=53c1fb45-030d-0004-02b7-16b5-00163e4c0d3f",
"startPoint": {
"lng": -74.189582,
"lat": 40.602352
},
"turnType": 2
}

Haven't tested it but here is the idea. You can use a function that will traverse object tree and collect items specified by a path.
function getPath(path, obj) {
var name, value;
path = path instanceof Array ? path: path.split('.'); //convert path to array
name = path.shift(); //get the first name
value = obj[name]; //extract value
if(!path.length || value == null) { //last name or value is null or undefined
return value;
}
if(value instanceof Array) { //if value is array - concat
return [].concat.apply([], value.map(function(item){
return getPath(path.slice(0), item);
}));
}
return getPath(path, value); //else go deeper
}
Usage:
var narratives
= getPath('renderMatrixResults.route.legs.maneuvers.narrative', mq);
I believe the path is correct.

Related

How to get common value in Object Array in JavaScript

const data = {
"games": [
{
"id": "828de9122149499183df39c6ae2dd3ab",
"developer_id": "885911",
"game_name": "Minecraft",
"first_release": "2011-18-11",
"website": "https://www.minecraft.net/en-us"
},
{
"id": "61ee6f196c58afc9c1f78831",
"developer_id": "810637",
"game_name": "Fortnite",
"first_release": "2017-21-07",
"website": "https://www.epicgames.com/fortnite/en-US/home"
},
],
"developers": [
{
"id": "885911",
"name": "Mojang Studios",
"country": "US",
"website": "http://www.mojang.com",
},
{
"id": "750245",
"name": "God of War",
"country": "SE",
"website": "https://sms.playstation.com",
},
] };
I have json data like this. I want to display data like if developer_id = 885911(from games array) then print id(from developers array) and if the both are same then I want to print the name.(Mojang studios) and so on like games website etc. How can I do that?
This sample code will show you the developer of each game, if it's found:
const data = {
"games": [
{
"id": "828de9122149499183df39c6ae2dd3ab",
"developer_id": "885911",
"game_name": "Minecraft",
"first_release": "2011-18-11",
"website": "https://www.minecraft.net/en-us"
},
{
"id": "61ee6f196c58afc9c1f78831",
"developer_id": "810637",
"game_name": "Fortnite",
"first_release": "2017-21-07",
"website": "https://www.epicgames.com/fortnite/en-US/home"
},
],
"developers": [
{
"id": "885911",
"name": "Mojang Studios",
"country": "US",
"website": "http://www.mojang.com",
},
{
"id": "750245",
"name": "God of War",
"country": "SE",
"website": "https://sms.playstation.com",
},
] };
const gameDevelopers = data.games.map(g => ({
game: g.game_name,
developer: data.developers.find(d => d.id === g.developer_id)?.name || "No matching developer found"
}));
console.log(gameDevelopers)
What did you exactly need? i don't understand . But you can get value Mojang Studios
console.log(data.developers[0].name)
If you need all developer id then you can use
console.log(data.developers.map(data=>{
console.log(data.id)
}))
If you need the id where name is Mojang Studios
console.log(data.developers.map(data=>{
if(data.name == "Mojang Studios"){
console.log(data.id)
}
}))

Reshaping Flat JSON Structures with JavaScript

Currently, I have data in a flat JSON format. We need to convert it to a particular structure.
[
{
"Region":"WEST",
"District":"PACIFIC",
"timestamp":"2018-12-28T00:00:00.000Z",
"Penetration":374
},
{
"Region":"WEST",
"District":"MOUNTAIN",
"timestamp":"2018-12-28T00:00:00.000Z",
"Penetration":427
},
{
"Region":"SOUTH",
"District":"SOUTH WEST",
"timestamp":"2018-12-28T00:00:00.000Z",
"Penetration":422
},
{
"Region":"SOUTH",
"District":"SOUTH EAST",
"timestamp":"2018-12-28T00:00:00.000Z",
"Penetration":410
}
]
It should be as such. Also a constant "version": "v1" needs to be added to each object. The flattened result-set can be dynamic. So apart from timestamp key whatever key-value pair are present shall be pulled inside event object.
[
{
"version": "v1",
"timestamp": "2018-12-28T00:00:00.000Z",
"event": {
"Penetration":374,
"Region": "WEST",
"District": "PACIFIC"
}
},
{
"version": "v1",
"timestamp": "2018-12-28T00:00:00.000Z",
"event": {
"Penetration":427,
"Region": "WEST",
"District": "MOUNTAIN"
}
},
{
"version": "v1",
"timestamp": "2018-12-28T00:00:00.000Z",
"event": {
"Penetration":422,
"Region": "SOUTH",
"District": "SOUTH WEST"
}
}
{
"version": "v1",
"timestamp": "2018-12-28T00:00:00.000Z",
"event": {
"Penetration":410
"Region": "SOUTH",
"District": "SOUTH EAST"
}
}
]
You can simply make use of map method:
var data=[ { "Region":"WEST", "District":"PACIFIC", "timestamp":"2018-12-28T00:00:00.000Z", "Penetration":374 }, { "Region":"WEST", "District":"MOUNTAIN", "timestamp":"2018-12-28T00:00:00.000Z", "Penetration":427 }, { "Region":"SOUTH", "District":"SOUTH WEST", "timestamp":"2018-12-28T00:00:00.000Z", "Penetration":422 }, { "Region":"SOUTH", "District":"SOUTH EAST", "timestamp":"2018-12-28T00:00:00.000Z", "Penetration":410 }];
var result = data.map(({timestamp, ...events})=>({version:'v1',timestamp, events}));
console.log(result);

Getting Error when converting json object to class type array in typescript

I am getting json object from service, i wanted to iterate to this json object and fill array of class type.
Following is the code to call the service
public GetMapData(): Observable<Response> {
var path = 'http://my.blog.net/blog.php?type=trendingDestiny';
return this.http.get(path)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json();
}
});
}
self.blogapi.GetMapData().subscribe(
x => {
this.MapData = x;
console.log("MapData", this.MapData);
});
Following is the json response
[
{
"post_id": 77,
"post_title": "Delhi",
"post_content": "DelhiDelhiDelhi",
"post_date": "2017-07-24 11:47:08",
"imageurl": false,
"cat_name": [
{
"term_id": 7,
"name": "FOODIE",
"slug": "foodie",
"category_parent": 0
}
],
"longitude": "75.857849",
"latitude": "33.888586",
"region_name": "Asia"
},
{
"post_id": 75,
"post_title": "Goa",
"post_content": "this is goa",
"post_date": "2017-07-24 11:03:59",
"imageurl": false,
"cat_name": [
{
"term_id": 7,
"name": "FOODIE",
"slug": "foodie",
"category_parent": 0
}
],
"longitude": "75.857849",
"latitude": "33.888586",
"region_name": "Asia"
}]
Following is the typescript code
this.MapData.forEach(map => {
this.Mapdatalist.push({
postid: map.post_id,
regionname: map.region_name,
longitude: map.longitude
});
});
or i also tried
for (let data of this.MapData)
{
console.log("error",data);
}
But nothing works. It gives me error
ERROR TypeError: Cannot read property 'forEach' of undefined
Please help what is going wrong.
var array= [
{
"post_id": 77,
"post_title": "Delhi",
"post_content": "DelhiDelhiDelhi",
"post_date": "2017-07-24 11:47:08",
"imageurl": false,
"cat_name": [
{
"term_id": 7,
"name": "FOODIE",
"slug": "foodie",
"category_parent": 0
}
],
"longitude": "75.857849",
"latitude": "33.888586",
"region_name": "Asia"
},
{
"post_id": 75,
"post_title": "Goa",
"post_content": "this is goa",
"post_date": "2017-07-24 11:03:59",
"imageurl": false,
"cat_name": [
{
"term_id": 7,
"name": "FOODIE",
"slug": "foodie",
"category_parent": 0
}
],
"longitude": "75.857849",
"latitude": "33.888586",
"region_name": "Asia"
}];
//console.log(array);
var mapdata = [];
$.each(array,function(i,v){
mapdata.push({"postid":v.post_id,"regionname":v.region_name,"longitude":v.longitude});
})
console.log(mapdata);
Please check that you assigned response to "this.MapData". I have created same scenario, where it is working. It might be case that "this.MapData" is not declared and defined correctly.

JavaScript GeoJson Parser

i have geojson data:
{
"type":"FeatureCollection",
"metadata":{
"generated":1417015873000,
11-26T14:33:40&endtime=2014-11-26T14:33:45",
"title":"USGS Earthquakes",
"status":200,
"api":"1.0.13",
"count":1
},
"features":
[{
"type":"Feature",
"properties":
{
"mag":6.8,
"place":"160km NW of Kota Ternate, Indonesia",
"time":1417012423350,"updated":1417015584000,
"tz":480,
"url":"http://comcat.cr.usgs.gov/earthquakes/eventpage/usb000t08w",
"detail":"http://comcat.cr.usgs.gov/fdsnws/event/1/query?eventid=usb000t08w&format=geojson",
"felt":1,
"cdi":5,
"mmi":4.98,
"alert":"green",
"status":"reviewed",
"tsunami":1,
"sig":712,
"net":"us",
"code":"b000t08w",
"ids":",at00nfnhsd,pt14330000,usb000t08w,",
"sources":",at,pt,us,",
"types":",cap,dyfi,general-link,geoserve,impact-link,losspager,moment-tensor,nearby-cities,origin,phase-data,shakemap,tectonic-summary,",
"nst":null,
"dmin":1.45,
"rms":1.32,
"gap":37,
"magType":"mwb",
"type":"earthquake",
"title":"M 6.8 - 160km NW of Kota Ternate, Indonesia"
},
"geometry":{"type":"Point","coordinates":[126.5456,1.9752,41.06]},
"id":"usb000t08w"
}]
}
how to parse value "title" ?
var geojson = JSON.parse(geojson_data);
Turns the geojson string into an object, from there you can get whatever you values you want from it.
Edit: your json is invalid, where are you getting the data from? I cleaned it up, so you can call JSON.parse on it. However, it is not valid geojson, so I'd double check where you come up with the data. This geojson validator might help.
{
"metadata": {
"generated": 1417015873000,
"11-26T14: 33: 40&endtime=2014-11-26T14: 33": 45,
"title": "USGSEarthquakes",
"status": 200,
"api": "1.0.13",
"count": 1
},
"features": [
{
"type": "Feature",
"properties": {
"mag": 6.8,
"place": "160km NW of Kota Ternate, Indonesia",
"time": 1417012423350,
"updated": 1417015584000,
"tz": 480,
"url": "http://comcat.cr.usgs.gov/earthquakes/eventpage/usb000t08w",
"detail": "http://comcat.cr.usgs.gov/fdsnws/event/1/query?eventid=usb000t08w&format=geojson",
"felt": 1,
"cdi": 5,
"mmi": 4.98,
"alert": "green",
"status": "reviewed",
"tsunami": 1,
"sig": 712,
"net": "us",
"code": "b000t08w",
"ids": ",at00nfnhsd,pt14330000,usb000t08w,",
"sources": ",at,pt,us,",
"types": ",cap,dyfi,general-link,geoserve,impact-link,losspager,moment-tensor,nearby-cities,origin,phase-data,shakemap,tectonic-summary,",
"nst": null,
"dmin": 1.45,
"rms": 1.32,
"gap": 37,
"magType": "mwb",
"type": "earthquake",
"title": "M 6.8 - 160km NW of Kota Ternate, Indonesia"
},
"geometry": {
"type": "Point",
"coordinates": [
126.5456,
1.9752,
41.06
]
},
"id": "usb000t08w"
}
]
}

How to sort foursquare venues by name (i.e. sorting

I'm using the foursquare venues API to populate a select menu and list in my web app. I'd like to sort the venues alphabetically by name.
Here is a JSON response from the foursquare API, which has some venues:
[ { "reasons": { "count": 1, "items": [ { "summary": "This spot is popular on foursquare", "type": "general", "reasonName": "globalInteractionReason" } ] }, "venue": { "id": "4c6ee03fb5a5236a74744b52", "name": "Peninsular Paper Dam", "contact": {}, "location": { "address": "1265 Leforge Rd", "crossStreet": "at Huron River Rd", "lat": 42.256628, "lng": -83.623933, "distance": 892, "postalCode": "48198", "city": "Ypsilanti", "state": "MI", "country": "United States", "cc": "US" }, "categories": [ { "id": "4bf58dd8d48988d165941735", "name": "Scenic Lookout", "pluralName": "Scenic Lookouts", "shortName": "Scenic Lookout", "icon": { "prefix": "https://foursquare.com/img/categories_v2/parks_outdoors/sceniclookout_", "suffix": ".png" }, "primary": true } ], "verified": false, "stats": { "checkinsCount": 31, "usersCount": 12, "tipCount": 0 }, "likes": { "count": 0, "groups": [] }, "specials": { "count": 0, "items": [] }, "photos": { "count": 2, "groups": [] } } }, { "reasons": { "count": 1, "items": [ { "summary": "This spot is popular on foursquare", "type": "general", "reasonName": "globalInteractionReason" } ] }, "venue": { "id": "4ba58202f964a520cb0d39e3", "name": "Benito's Pizza", "contact": { "phone": "7349610707", "formattedPhone": "(734) 961-0707" }, "location": { "address": "1088 N Huron River Dr", "lat": 42.256532, "lng": -83.629082, "distance": 1035, "postalCode": "48197", "city": "Ypsilanti", "state": "MI", "country": "United States", "cc": "US" }, "categories": [ { "id": "4bf58dd8d48988d1ca941735", "name": "Pizza Place", "pluralName": "Pizza Places", "shortName": "Pizza", "icon": { "prefix": "https://foursquare.com/img/categories_v2/food/pizza_", "suffix": ".png" }, "primary": true } ], "verified": false, "stats": { "checkinsCount": 50, "usersCount": 34, "tipCount": 0 }, "url": "http://www.benitospizza.com/", "likes": { "count": 0, "groups": [] }, "menu": { "type": "foodAndBeverage", "url": "https://foursquare.com/v/benitos-pizza/4ba58202f964a520cb0d39e3/menu", "mobileUrl": "https://foursquare.com/v/4ba58202f964a520cb0d39e3/device_menu" }, "specials": { "count": 0, "items": [] }, "photos": { "count": 0, "groups": [] } } } ]
I'm able to parse this response with this code:
for (var i = 0; i < venues.length; i++) {
name = venues[i]['venue']['name'];
category = venues[i]['venue']['categories'][0]['name'];
icon = venues[i]['venue']['categories'][0]['icon']['prefix'];
icon = icon.slice(0, -1); // remove trailing "_" character
icon = icon + venues[i]['venue']['categories'][0]['icon']['suffix'];
address = venues[i]['venue']['location']['address'];
city = venues[i]['venue']['location']['city'];
state = venues[i]['venue']['location']['state'];
distance_meters = venues[i]['venue']['location']['distance'];
distance_miles = distance_meters / 1609.34;
distance_miles = Math.round(distance_miles*100)/100;
x = 1; // in the product use i for index below
HTMLmarkupList += "<li><img src=\"" + icon + "\" class=\"ui-li-thumb\" style=\"margin: 23px 10px\" onerror=\"ImgError(this);\">" + "<h3 style=\"margin-left: -40px\">" + name + "</h3><p style=\"margin-left: -40px\">" + category + "</p><p style=\"margin-left: -40px\">" + address + ", " + city + ", " + state + "</p><p style=\"margin-left: -40px\">" + distance_miles + " miles from you.</p></li>";
HTMLmarkupSelect += "<option value\"" + i + "\">" + name + "</option>";
}
Right now, the value of the select is just i, but as I'll be needing to store other variables along with the name in my database I may update the value in each select option to include things like the address, city, state, etc.... I mention this because if I was only using the name in the select, I could just build an array of names and use the javascript sort method.
Can anyone help with how to sort the venues alphabetically by name? Thanks.
Information:
http://www.w3schools.com/jsref/jsref_sort.asp
Example:
venues.sort(function(a,b){
if(a.venue.name == b.venue.name) return 0;
return (a.venue.name < b.venue.name) ? -1 : 1;
});

Categories