Extract and rename JSON object to different format - javascript

I'm requesting venue data from the Foursquare API but it is not returned in the geoJSON format. I haven't worked with JSON before and I do not have any idea how to approach doing this.
Will I loop through the object and build a JavaScript array of the necessary object values ? How do I select all of the values with the same key ? Is it possible just to delete particular values out of the JSON response and rename the others as desired ? What is the best approach here ?
Below I have posted both the input and the desired output of what I would like to achieve.
INPUT
{
"meta": {
"code": 200,
"requestId": "57c63303498e78d449981c2c"
},
"response": {
"venues": [{
"id": "430d0a00f964a5203e271fe3",
"name": "Brooklyn Bridge Park",
"location": {
"address": "Main St",
"crossStreet": "Plymouth St",
"lat": 40.70303245363086,
"lng": -73.99389265510275
}
}, {
"id": "51eabef6498e10cf3aea7942",
"name": "Brooklyn Bridge Park - Pier 2",
"contact": {},
"location": {
"address": "Furman St",
"crossStreet": "Brooklyn Bridge Park Greenway",
"lat": 40.69957016220183,
"lng": -73.99793274204788
}
}]
}
}
OUTPUT
[{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [-73.99389265510277, 40.703032453630854]
},
"properties": {
"id": "430d0a00f964a5203e271fe3",
"name": "Brooklyn Bridge Park",
"location": {
"address": "Main St",
"crossStreet": "Plymouth St",
"lat": 40.703032453630854,
"lng": -73.99389265510277
}
}
}, {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [-73.9979327420479, 40.69957016220184]
},
"properties": {
"id": "51eabef6498e10cf3aea7942",
"name": "Brooklyn Bridge Park - Pier 2",
"location": {
"address": "Furman St",
"crossStreet": "Brooklyn Bridge Park Greenway",
"lat": 40.69957016220184,
"lng": -73.9979327420479
}
}
}]

You can do this by saving the response into variable. Don't forget to JSON.parse it. Then you can do the following to convert it into your own format by using Array#map method.
let obj = {
"meta": {
"code": 200,
"requestId": "57c63303498e78d449981c2c"
},
"response": {
"venues": [{
"id": "430d0a00f964a5203e271fe3",
"name": "Brooklyn Bridge Park",
"location": {
"address": "Main St",
"crossStreet": "Plymouth St",
"lat": 40.70303245363086,
"lng": -73.99389265510275
}
}, {
"id": "51eabef6498e10cf3aea7942",
"name": "Brooklyn Bridge Park - Pier 2",
"contact": {},
"location": {
"address": "Furman St",
"crossStreet": "Brooklyn Bridge Park Greenway",
"lat": 40.69957016220183,
"lng": -73.99793274204788
}
}]
}
};
let res = obj.response.venues.map((venue) => {
let o = {};
o.type = "feature";
o.geometry = {
type: "Point",
coordinates: [venue.location.lng, venue.location.lat]
};
o.properties = venue;
return o;
});
console.log(res);

You can save the result from your request to the Foursquare API as a variable and then loop through it to get the information you need:
var result = {
"meta": {
"code": 200,
"requestId": "57c63303498e78d449981c2c"
},
"response": {
"venues": [{
"id": "430d0a00f964a5203e271fe3",
"name": "Brooklyn Bridge Park",
"location": {
"address": "Main St",
"crossStreet": "Plymouth St",
"lat": 40.70303245363086,
"lng": -73.99389265510275
}
}, {
"id": "51eabef6498e10cf3aea7942",
"name": "Brooklyn Bridge Park - Pier 2",
"contact": {},
"location": {
"address": "Furman St",
"crossStreet": "Brooklyn Bridge Park Greenway",
"lat": 40.69957016220183,
"lng": -73.99793274204788
}
}]
}
}
for(i=0;i<result.response.venues.length;i++) {
console.log(result.response.venues[i].name)
}
Console Result:
Brooklyn Bridge Park
Brooklyn Bridge Park - Pier 2
Instead of logging this to the console, you could then write the data into a new JS object the way you described in your output. Question is, do you really need to? The information is right there... rewriting it to a new object should not be necessary.

Related

Verify String is displaying within Nested JSON using Postman

I am working on Postman to verify some API calls, upon which I have gone through one of the end point, whose response is give below, and I need to make sure that within that JSON response:
[
{
"contact": {
"id": "k72yk2iwrf",
"firstName": "Francis",
"lastName": "Abell",
"title": "Translational Science Project Manager",
"company": "Sensei",
"email": "aa#aa.cpom",
"fax": {},
"businessAddress": {
"line1": "road",
"line2": "Street",
"line3": "Suite 710",
"city": "Boston",
"country": "US",
"postalCode": "02210",
"state": "MA"
},
"businessPhone": {
"number": "123-123-1234",
"ext": ""
},
"homeAddress": {},
"homePhone": {},
"mobilePhone": {}
},
"registration": {
"id": "104656",
"badgeId": "9208113975",
"eventId": "TESTLIBRA-10"
}
},
{
"contact": {
"id": "w4c4f2i7l4",
"firstName": "Francis",
"lastName": "Abell",
"title": "Translational Science Project Manager",
"company": "Sensei",
"email": "aa#aa.cpom",
"fax": {},
"businessAddress": {
"line1": "road",
"line2": "Street",
"line3": "Suite 710",
"city": "Boston",
"country": "US",
"postalCode": "02210",
"state": "MA"
},
"businessPhone": {
"number": "123-123-1234",
"ext": ""
},
"homeAddress": {},
"homePhone": {},
"mobilePhone": {}
},
"registration": {
"id": "104656",
"badgeId": "6803424516",
"eventId": "TESTLIBRA-10"
}
}
]
I can make sure that "eventId" is displaying and it is displaying "TESTLIBRA-10" value.
No matter, how long JSON response is, It can verify that this property , along with that value of that property are displaying.
I got my answer by myself, what I did was:
var jsonArrayData = pm.response.json();
pm.test('EventID property is displaying throughout JSON', function(){
jsonArrayData.each(function(eventID){
pm.expect(eventID.registration).to.have.property("eventId")
})
})
pm.test('Entered Libra EventID is entered', function(){
jsonArrayData.each(function(eventID){
pm.expect(eventID.registration.eventId).to.eql("TESTLIBRA-10")
})
})

Angular pick up an item within an array

I'm using angular to manipulate a tmdb api, but I'm having trouble getting an item that is inside an array, could you help me?
the answer that the array returns to me is this:
{
"id": 423108,
"results": [{
"id": "608177732da846006e382e45",
"iso_639_1": "en",
"iso_3166_1": "US",
"key": "qc6jN1BcJi0",
"name": "Official Trailer – Warner Bros. UK & Ireland",
"site": "YouTube",
"size": 1080,
"type": "Trailer"
}, {
"id": "6081f2879e45860058f36147",
"iso_639_1": "en",
"iso_3166_1": "US",
"key": "h9Q4zZS2v1k",
"name": "Official Trailer",
"site": "YouTube",
"size": 1080,
"type": "Trailer"
}, {
"id": "60a3f3d8cb75d1003f6cad3f",
"iso_639_1": "en",
"iso_3166_1": "US",
"key": "6Eb1V9gJ5Z4",
"name": "Chasing Evil Featurette",
"site": "YouTube",
"size": 1080,
"type": "Featurette"
}, {
"id": "60a7f244e16e5a003f89fcfb",
"iso_639_1": "en",
"iso_3166_1": "US",
"key": "4GjhydkUMrQ",
"name": "The Conjuring: The Devil Made Me Do It - Demonic Possession Featurette - Warner Bros. UK",
"site": "YouTube",
"size": 1080,
"type": "Featurette"
}, {
"id": "60b65a605c563400782c09c4",
"iso_639_1": "en",
"iso_3166_1": "US",
"key": "5FEdg3FhiGc",
"name": "Final Trailer – Warner Bros. UK & Ireland",
"site": "YouTube",
"size": 1080,
"type": "Trailer"
}, {
"id": "60b6e54aefd3c20041e08f6b",
"iso_639_1": "en",
"iso_3166_1": "US",
"key": "AB9mPsH2z1U",
"name": "The Conjuring: The Devil Made Me Do It | 2021 | Clip: "
Mitigating Circumstances " HD",
"site": "YouTube",
"size": 1080,
"type": "Clip"
}, {
"id": "60b9622aabf8e2006fb33499",
"iso_639_1": "en",
"iso_3166_1": "US",
"key": "tLFnRAzcaEc",
"name": "Final Trailer",
"site": "YouTube",
"size": 1080,
"type": "Trailer"
}, {
"id": "60be2d10960cde006d905ecf",
"iso_639_1": "en",
"iso_3166_1": "US",
"key": "2V2MmKkddM0",
"name": "The Conjuring: The Devil Made Me Do It - Teaser",
"site": "YouTube",
"size": 1080,
"type": "Teaser"
}]
}
And I want to get the "key" item. The idea is to get the key and then concatenate it with the youtube link to redirect to the trailer on youtube, or put the youtube player in the application. I'm currently doing it this way:
this.clientService.getVideoID(this.id).subscribe(data => this.video = date)
But I only have access to video.results, I can't give video.results.key
it seems there is a problem in this JSON element because it contains "
You can use the filter() function like so
const myVideo = results.filter(item => item.id === "608177732da846006e382e45")[0]
note that it will only work if the id is unique, filter returns an array filled with item that return true on the condition ( item.key === "608177732da846006e382e45"), and then we take the 1st one which is supposed to be the only one.
and then you can access myVideo.key
Obviously replace "608177732da846006e382e45" with whatever your input is

JavaScript access object

How can I get the "name" of the following JSON object?
"location": {
"name": "Hilden",
"country": "Germany",
"region": "Nordrhein-Westfalen",
"lat": "51.167",
"lon": "6.933",
"timezone_id": "Europe/Berlin",
"localtime": "2020-04-22 15:03",
"localtime_epoch": 1587567780,
"utc_offset": "2.0"
}
["name"] returns the followin error
TypeError: Cannot read property 'name' of undefined
This could help you if not then let me know. If your json object is same as your_json_obj then you have to parse it first using JSON.parse(your_json_obj). If not then you simply use your_json_obj.location.name
const your_json_obj = "{
"location": {
"name": "Hilden",
"country": "Germany",
"region": "Nordrhein-Westfalen",
"lat": "51.167",
"lon": "6.933",
"timezone_id": "Europe/Berlin",
"localtime": "2020-04-22 15:03",
"localtime_epoch": 1587567780,
"utc_offset": "2.0"
},
...}"
const name = JSON.parse(your_json_obj).location.name
console.log(name)
You can access its properties using location.name, location["name"], for example:
const location = {
"name": "Hilden",
"country": "Germany",
"region": "Nordrhein-Westfalen",
"lat": "51.167",
"lon": "6.933",
"timezone_id": "Europe/Berlin",
"localtime": "2020-04-22 14:44",
"localtime_epoch": 1587566640,
"utc_offset": "2.0"
}
location.name;
location.["name"]
If you want to use it from the JSON object:
var y = '{"location": { "name": "Hilden", "country": "Germany", "region": "Nordrhein-Westfalen", "lat": "51.167", "lon": "6.933", "timezone_id": "Europe/Berlin", "localtime": "2020-04-22 15:03", "localtime_epoch": 1587567780, "utc_offset": "2.0" }}';
JSON.parse(y).location.name
So, in this case, you should use JSON.parse(jsonObject)) before access its properties. BUT NOTICE: "Make sure the text is written in JSON format, or else you will get a syntax error.", a "large text" inside {} - https://www.w3schools.com/js/js_json_parse.asp

How to destructure json data in JavaScript

Giving this json data , how can I Modify it to use object de-structuring to get just the dob property of the parameter object, having troubles understanding please
{
"results":[
{
"gender":"female",
"name":{
"title":"ms",
"first":"emily",
"last":"simmons"
},
"location":{
"street":"1514 preston rd",
"city":"mackay",
"state":"victoria",
"postcode":3943,
"coordinates":{
"latitude":"-82.6428",
"longitude":"99.3586"
},
"timezone":{
"offset":"-5:00",
"description":"Eastern Time (US & Canada), Bogota, Lima"
}
},
"email":"emily.simmons#example.com",
"login":{
"uuid":"4db43a8c-f811-4f66-9063-8de9af1b7ff4",
"username":"brownlion857",
"password":"girls",
"salt":"Fff9zzxa",
"md5":"4eb010fc1f3e9f72b6298b75cec001a1",
"sha1":"086f0a1c0db596967033a77df62e21e6d407f647",
"sha256":"d7f99aae053957d788fe17a80922877d04a491bd7ea00d7b6b41c94329468e12"
},
"dob":{
"date":"1992-10-20T03:47:03Z",
"age":26
},
"registered":{
"date":"2012-02-25T19:05:12Z",
"age":7
},
"phone":"09-1749-9293",
"cell":"0490-139-057",
"id":{
"name":"TFN",
"value":"338334455"
},
"picture":{
"large":"https://randomuser.me/api/portraits/women/64.jpg",
"medium":"https://randomuser.me/api/portraits/med/women/64.jpg",
"thumbnail":"https://randomuser.me/api/portraits/thumb/women/64.jpg"
},
"nat":"AU"
}
],
"info":{
}
}
I did something like this:
const displayBirthdate = ( {results: [{dob: {date, age } }]}) =>
{
}
Is there a way I can make it simpler to just get the dob parameter for the function?
You can declare your variables using Destructuring assignment:
const json = {"results": [{"gender": "female","name": {"title": "ms","first": "emily","last": "simmons"},"location": {"street": "1514 preston rd","city": "mackay","state": "victoria","postcode": 3943,"coordinates": { "latitude": "-82.6428", "longitude": "99.3586"},"timezone": { "offset": "-5:00", "description": "Eastern Time (US & Canada), Bogota, Lima"}},"email": "emily.simmons#example.com","login": {"uuid": "4db43a8c-f811-4f66-9063-8de9af1b7ff4","username": "brownlion857","password": "girls","salt": "Fff9zzxa","md5": "4eb010fc1f3e9f72b6298b75cec001a1","sha1": "086f0a1c0db596967033a77df62e21e6d407f647","sha256": "d7f99aae053957d788fe17a80922877d04a491bd7ea00d7b6b41c94329468e12"},"dob": {"date": "1992-10-20T03:47:03Z","age": 26},"registered": {"date": "2012-02-25T19:05:12Z","age": 7},"phone": "09-1749-9293","cell": "0490-139-057","id": {"name": "TFN","value": "338334455"},"picture": {"large": "https://randomuser.me/api/portraits/women/64.jpg","medium": "https://randomuser.me/api/portraits/med/women/64.jpg","thumbnail": "https://randomuser.me/api/portraits/thumb/women/64.jpg"},"nat": "AU"}],"info": {}};
const {results: [{dob: {date, age}}]} = json;
console.log('date:', date);
console.log('age:', age);
According to the comment:
how would i make it a function parameter, like dob for instance?
const json = {"results": [{"gender": "female","name": {"title": "ms","first": "emily","last": "simmons"},"location": {"street": "1514 preston rd","city": "mackay","state": "victoria","postcode": 3943,"coordinates": { "latitude": "-82.6428", "longitude": "99.3586"},"timezone": { "offset": "-5:00", "description": "Eastern Time (US & Canada), Bogota, Lima"}},"email": "emily.simmons#example.com","login": {"uuid": "4db43a8c-f811-4f66-9063-8de9af1b7ff4","username": "brownlion857","password": "girls","salt": "Fff9zzxa","md5": "4eb010fc1f3e9f72b6298b75cec001a1","sha1": "086f0a1c0db596967033a77df62e21e6d407f647","sha256": "d7f99aae053957d788fe17a80922877d04a491bd7ea00d7b6b41c94329468e12"},"dob": {"date": "1992-10-20T03:47:03Z","age": 26},"registered": {"date": "2012-02-25T19:05:12Z","age": 7},"phone": "09-1749-9293","cell": "0490-139-057","id": {"name": "TFN","value": "338334455"},"picture": {"large": "https://randomuser.me/api/portraits/women/64.jpg","medium": "https://randomuser.me/api/portraits/med/women/64.jpg","thumbnail": "https://randomuser.me/api/portraits/thumb/women/64.jpg"},"nat": "AU"}],"info": {}};
const getDate = dob => ({date, age} = dob);
console.log('displayBirthdate:', getDate(json.results[0].dob));
You could combine de-structuring with mapping for more readable code:
const data = {
"results": [{
"gender": "female",
"name": {
"title": "ms",
"first": "emily",
"last": "simmons"
},
"location": {
"street": "1514 preston rd",
"city": "mackay",
"state": "victoria",
"postcode": 3943,
"coordinates": {
"latitude": "-82.6428",
"longitude": "99.3586"
},
"timezone": {
"offset": "-5:00",
"description": "Eastern Time (US & Canada), Bogota, Lima"
}
},
"email": "emily.simmons#example.com",
"login": {
"uuid": "4db43a8c-f811-4f66-9063-8de9af1b7ff4",
"username": "brownlion857",
"password": "girls",
"salt": "Fff9zzxa",
"md5": "4eb010fc1f3e9f72b6298b75cec001a1",
"sha1": "086f0a1c0db596967033a77df62e21e6d407f647",
"sha256": "d7f99aae053957d788fe17a80922877d04a491bd7ea00d7b6b41c94329468e12"
},
"dob": {
"date": "1992-10-20T03:47:03Z",
"age": 26
},
"registered": {
"date": "2012-02-25T19:05:12Z",
"age": 7
},
"phone": "09-1749-9293",
"cell": "0490-139-057",
"id": {
"name": "TFN",
"value": "338334455"
},
"picture": {
"large": "https://randomuser.me/api/portraits/women/64.jpg",
"medium": "https://randomuser.me/api/portraits/med/women/64.jpg",
"thumbnail": "https://randomuser.me/api/portraits/thumb/women/64.jpg"
},
"nat": "AU"
}],
"info": {}
}
const [ dob ] = data.results.map(item => item.dob)
console.log(dob)
// {date: "1992-10-20T03:47:03Z", age: 26}

Unhandled promise rejection: TypeError: undefined is not a function evaluating 'departureloc.map' occurs when mapping for setState in react native

I am successful on getting through the JSON response from Google Directions as i am trying to get to the transit information from the json response which is initially looks like this when successful.
Object {
"geocoded_waypoints": Array [
Object {
"geocoder_status": "OK",
"place_id": "ChIJ2YDFT9zweUgRgt5Tws6n3hs",
"types": Array [
"premise",
],
},
Object {
"geocoder_status": "OK",
"place_id": "ChIJW2PCihXxeUgRRWgA9kOzpjY",
"types": Array [
"establishment",
"food",
"lodging",
"point_of_interest",
"restaurant",
],
},
],
"routes": Array [
Object {
"bounds": Object {
"northeast": Object {
"lat": 52.9242042,
"lng": -1.466251,
},
"southwest": Object {
"lat": 52.9004767,
"lng": -1.4801554,
},
},
"copyrights": "Map data ©2018 Google",
"legs": Array [
Object {
"arrival_time": Object {
"text": "9:21am",
"time_zone": "Europe/London",
"value": 1524558107,
},
"departure_time": Object {
"text": "8:56am",
"time_zone": "Europe/London",
"value": 1524556589,
},
"distance": Object {
"text": "3.4 km",
"value": 3407,
},
"duration": Object {
"text": "25 mins",
"value": 1518,
},
"end_address": "Full St, Derby DE1 3AF, UK",
"end_location": Object {
"lat": 52.9242042,
"lng": -1.4756769,
},
"start_address": "50 Chatham St, Derby DE23 8TH, UK",
"start_location": Object {
"lat": 52.9004767,
"lng": -1.480144,
},
"steps": Array [
Object {
"distance": Object {
"text": "0.2 km",
"value": 175,
},
"duration": Object {
"text": "2 mins",
"value": 123,
},
"end_location": Object {
"lat": 52.900963,
"lng": -1.478217,
},
"html_instructions": "Walk to Randolph Road",
"polyline": Object {
"points": "_c{aIza`Hm#BEyHC_Ag#S?H",
},
"start_location": Object {
"lat": 52.9004767,
"lng": -1.480144,
},
"steps": Array [
Object {
"distance": Object {
"text": "26 m",
"value": 26,
},
"duration": Object {
"text": "1 min",
"value": 18,
},
"end_location": Object {
"lat": 52.9007148,
"lng": -1.4801554,
},
"html_instructions": "Head <b>north</b> on <b>Chatham St</b> toward <b>Randolph Rd</b>",
"polyline": Object {
"points": "_c{aIza`Hm#B",
},
"start_location": Object {
"lat": 52.9004767,
"lng": -1.480144,
},
"travel_mode": "WALKING",
},
Object {
"distance": Object {
"text": "0.1 km",
"value": 126,
},
"duration": Object {
"text": "1 min",
"value": 88,
},
"end_location": Object {
"lat": 52.9007561,
"lng": -1.4782714,
},
"html_instructions": "Turn <b>right</b> onto <b>Randolph Rd</b>",
"maneuver": "turn-right",
"polyline": Object {
"points": "md{aI~a`HEyHC_A",
},
"start_location": Object {
"lat": 52.9007148,
"lng": -1.4801554,
},
"travel_mode": "WALKING",
},
Object {
"distance": Object {
"text": "23 m",
"value": 23,
},
"duration": Object {
"text": "1 min",
"value": 17,
},
"end_location": Object {
"lat": 52.900963,
"lng": -1.478217,
},
"html_instructions": "Turn <b>left</b> onto <b>St Thomas Rd</b><div style=\"font-size:0.9em\">Destination will be on the left</div>",
"maneuver": "turn-left",
"polyline": Object {
"points": "wd{aIdv_Hg#S?H",
},
"start_location": Object {
"lat": 52.9007561,
"lng": -1.4782714,
},
"travel_mode": "WALKING",
},
],
"travel_mode": "WALKING",
},
Object {
"distance": Object {
"text": "2.5 km",
"value": 2460,
},
"duration": Object {
"text": "15 mins",
"value": 900,
},
"end_location": Object {
"lat": 52.91829079999999,
"lng": -1.4748049,
},
"html_instructions": "Bus towards Derby",
"polyline": Object {
"points": "_f{aIzu_HsPw#eHgW_IkOmHcPoLiNgKxQwHvL{LxKuK`G",
},
"start_location": Object {
"lat": 52.900963,
"lng": -1.478217,
},
"transit_details": Object {
"arrival_stop": Object {
"location": Object {
"lat": 52.91829079999999,
"lng": -1.4748049,
},
"name": "Osmaston Road (Stop A8)",
},
"arrival_time": Object {
"text": "9:13am",
"time_zone": "Europe/London",
"value": 1524557580,
},
"departure_stop": Object {
"location": Object {
"lat": 52.900963,
"lng": -1.478217,
},
"name": "Randolph Road",
},
"departure_time": Object {
"text": "8:58am",
"time_zone": "Europe/London",
"value": 1524556715,
},
"headsign": "Derby",
"line": Object {
"agencies": Array [
Object {
"name": "Arriva Midlands",
"url": "http://www.traveline.info/",
},
],
"color": "#11416d",
"name": "Sapphire 38",
"text_color": "#ffffff",
"vehicle": Object {
"icon": "//maps.gstatic.com/mapfiles/transit/iw2/6/bus2.png",
"name": "Bus",
"type": "BUS",
},
},
"num_stops": 9,
},
"travel_mode": "TRANSIT",
},
Object {
"distance": Object { ... truncated from a larger response...
To debug my code my fetch function consists console.log() my attempt on trying to get to the data that i need, i particularly need to get to the departure information and i believe i am successful of doing so, here is my attempt:
fetch('https://maps.googleapis.com/maps/api/directions/json?origin=' + latitude + ',' + longitude + '&destination=' + goingto + '&mode=transit&transit_mode=bus&key=' + apiDirectionskey)
.then((resdirections) => resdirections.json())
.then((responseJson4) => {
const departureloc = responseJson4.routes[0].legs[0].steps[1];
console.log(departureloc);
the code above leads to the following JSON result:
Object {
"distance": Object {
"text": "3.1 km",
"value": 3129,
},
"duration": Object {
"text": "20 mins",
"value": 1200,
},
"end_location": Object {
"lat": 52.92222599999999,
"lng": -1.471283,
},
"html_instructions": "Bus towards Derby",
"polyline": Object {
"points": "_f{aIzu_HsPw#eHgW_IkOmHcPoLiNgKxQwHvL{LxKuK`G{AqEJoPcU`A",
},
"start_location": Object {
"lat": 52.900963,
"lng": -1.478217,
},
"transit_details": Object {
"arrival_stop": Object {
"location": Object {
"lat": 52.92222599999999,
"lng": -1.471283,
},
"name": "Bus Station (Bay 19)",
},
"arrival_time": Object {
"text": "9:45am",
"time_zone": "Europe/London",
"value": 1524645900,
},
"departure_stop": Object {
"location": Object {
"lat": 52.900963,
"lng": -1.478217,
},
"name": "Randolph Road",
},
"departure_time": Object {
"text": "9:24am",
"time_zone": "Europe/London",
"value": 1524644676,
},
"headsign": "Derby",
"line": Object {
"agencies": Array [
Object {
"name": "Arriva Midlands",
"url": "http://www.traveline.info/",
},
],
"color": "#11416d",
"name": "Sapphire 38",
"text_color": "#ffffff",
"vehicle": Object {
"icon": "//maps.gstatic.com/mapfiles/transit/iw2/6/bus2.png",
"name": "Bus",
"type": "BUS",
},
},
"num_stops": 12,
},
"travel_mode": "TRANSIT",
}
as it shows it returns the actual JSON information that i need, and i want the transit information particularly the departure_stop location which looks like this:
"departure_stop": Object {
"location": Object {
"lat": 52.900963,
"lng": -1.478217,
},
"name": "Randolph Road",
}
I am in the process acquiring this data of the departure location so i can setState(). after initial tries of attempting to use .map() so i can aquire at latitude and longitude values, i am failing to get to do so as i am getting this:
[Unhandled promise rejection: TypeError: undefined is not a function (evaluating 'departureloc.map')]
Here is my attempt:
fetch('https://maps.googleapis.com/maps/api/directions/json?origin=' + latitude + ',' + longitude + '&destination=' + goingto + '&mode=transit&transit_mode=bus&key=' + apiDirectionskey)
.then((resdirections) => resdirections.json())
.then((responseJson4) => {
//const departureloc = responseJson4.routes[0].legs[0].steps[1];
const departureloc = responseJson4.routes[0].legs[0].steps[1];
console.log(departureloc);
let busscoords = departureloc.map((outcome) => {
return ( {
latitude: console.log(outcome.departure_stop.location.lat),
//longitude: outcome.departure_stop.location.lng,
});
});
//this.setState(console.log({ departureloc }));
});
}
Have i missed something? or what is my mistake? Any pointers on how to do this properly would be greatly appreciated. Thanks
actual JSON from:
const departureloc = responseJson4.routes[0].legs[0].steps[1];
console.log(departureloc);
Object {
"distance": Object {
"text": "3.1 km",
"value": 3129,
},
"duration": Object {
"text": "21 mins",
"value": 1260,
},
"end_location": Object {
"lat": 52.92222599999999,
"lng": -1.471283,
},
"html_instructions": "Bus towards Derby",
"polyline": Object {
"points": "_f{aIzu_HsPw#eHgW_IkOmHcPoLiNgKxQwHvL{LxKuK`G{AqEJoPcU`A",
},
"start_location": Object {
"lat": 52.900963,
"lng": -1.478217,
},
"transit_details": Object {
"arrival_stop": Object {
"location": Object {
"lat": 52.92222599999999,
"lng": -1.471283,
},
"name": "Bus Station (Bay 19)",
},
"arrival_time": Object {
"text": "4:14pm",
"time_zone": "Europe/London",
"value": 1524669240,
},
"departure_stop": Object {
"location": Object {
"lat": 52.900963,
"lng": -1.478217,
},
"name": "Randolph Road",
},
"departure_time": Object {
"text": "3:52pm",
"time_zone": "Europe/London",
"value": 1524667961,
},
"headsign": "Derby",
"line": Object {
"agencies": Array [
Object {
"name": "Arriva Midlands",
"url": "http://www.traveline.info/",
},
],
"color": "#11416d",
"name": "Sapphire 38",
"text_color": "#ffffff",
"vehicle": Object {
"icon": "//maps.gstatic.com/mapfiles/transit/iw2/6/bus2.png",
"name": "Bus",
"type": "BUS",
},
},
"num_stops": 12,
},
"travel_mode": "TRANSIT",
}
Since departureloc is an Object, therefore you cannot use .map on it
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
If you need to map on Object, use the Object.keys as it returns an array of a given object's properties names and use setState based on the key' properties.
and add a condition not to return undefined values as
Object.keys(departureloc).map(value => {
if(departureloc[value] && departureloc[value].lat) {
return //...
}
}

Categories

Resources