Output formatted json to a console.log - javascript

I have ajax which brings me back json,
What I want is to output everything inside 'routes' to a console.log but I don't know how to do that.
This is json output:
{
"geocoded_waypoints": [
{
"geocoder_status": "OK",
"place_id": "ChIJuVnJ34G3e0gRW_oSYLOUxEc",
"types": [
"premise"
]
},
{
"geocoder_status": "OK",
"place_id": "ChIJ0afvWH-3e0gRehrvBJAsflw",
"types": [
"premise"
]
}
],
"routes": [
{
"bounds": {
"northeast": {
"lat": 53.541228,
"lng": -2.1114936
},
"southwest": {
"lat": 53.5406464,
"lng": -2.1120657
}
},
"copyrights": "Dane do Mapy ©2017 Google",
"legs": [
{
"distance": {
"text": "0,1 km",
"value": 112
},
"duration": {
"text": "1 min",
"value": 27
},
"end_address": "Broseley House, 81 Union St, Oldham OL1 1PF, Wielka Brytania",
"end_location": {
"lat": 53.5406464,
"lng": -2.1120657
},
"start_address": "Ashton Arms, Oldham, Wielka Brytania",
"start_location": {
"lat": 53.5411486,
"lng": -2.1114936
},
"steps": [
{
"distance": {
"text": "39 m",
"value": 39
},
"duration": {
"text": "1 min",
"value": 7
},
"end_location": {
"lat": 53.54116,
"lng": -2.1119794
},
"html_instructions": "Kieruj się <b>Clegg St</b> na <b>północny zachód</b> w stronę <b>Ascroft St</b>",
"polyline": {
"points": "egxeIxk{KEBEDADAF?H#JJr#"
},
"start_location": {
"lat": 53.5411486,
"lng": -2.1114936
},
"travel_mode": "DRIVING"
},
{
"distance": {
"text": "52 m",
"value": 52
},
"duration": {
"text": "1 min",
"value": 11
},
"end_location": {
"lat": 53.5407078,
"lng": -2.1117626
},
"html_instructions": "Skręć <b>w lewo</b> w <b>Harrison St</b>",
"maneuver": "turn-left",
"polyline": {
"points": "ggxeIzn{KxAk#"
},
"start_location": {
"lat": 53.54116,
"lng": -2.1119794
},
"travel_mode": "DRIVING"
},
{
"distance": {
"text": "21 m",
"value": 21
},
"duration": {
"text": "1 min",
"value": 9
},
"end_location": {
"lat": 53.5406464,
"lng": -2.1120657
},
"html_instructions": "Skręć <b>w prawo</b> w <b>Printer St</b>",
"maneuver": "turn-right",
"polyline": {
"points": "mdxeInm{KJ|#"
},
"start_location": {
"lat": 53.5407078,
"lng": -2.1117626
},
"travel_mode": "DRIVING"
}
],
"traffic_speed_entry": [],
"via_waypoint": []
}
],
"overview_polyline": {
"points": "egxeIxk{KKHCL#TJr#xAk#J|#"
},
"summary": "Ascroft St i Harrison St",
"warnings": [],
"waypoint_order": []
}
],
"status": "OK"
}
How can I sort this json so I will only output everything inside routes?
Ajax:
function getDirections(lat, lng, destinationLat, destinationLng) {
$.ajax({
url: '/google',
type: 'post',
data: { lat: lat, lng: lng, destinationLat: destinationLat, destinationLng: destinationLng },
dataType: 'json',
success: function(data) {
console.log(data.routes);
},
error: function() { alert('boo!'); },
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
}
Controller:
function getGoogle() {
$lat = Input::get('lat');
$lng = Input::get('lng');
$destinationLat = Input::get('destinationLat');
$destinationLng = Input::get('destinationLng');
$google = file_get_contents('https://maps.googleapis.com/maps/api/directions/json?origin='.$lat.','.$lng.'&destination='.$destinationLat.','.$destinationLng.'&key=AIzaSyAirYgs4Xnt9QabG9v56jsIcCNfNZazq50');
return response()->json(['data' => $google]);
}
//edit
console.log(data);
Object {data: "{↵ "geocoded_waypoints" : [↵ {↵ "ge…t_order" : []↵ }↵ ],↵ "status" : "OK"↵}↵"}data: "{↵ "geocoded_waypoints" : [↵ {↵ "geocoder_status" : "OK",↵ "place_id" : "ChIJuVnJ34G3e0gRW_oSYLOUxEc",↵ "types" : [ "premise" ]↵ },↵ {↵ "geocoder_status" : "OK",↵ "place_id" : "ChIJ0afvWH-3e0gRehrvBJAsflw",↵ "types" : [ "premise" ]↵ }↵ ],↵ "routes" : [↵ {↵ "bounds" : {↵ "northeast" : {↵ "lat" : 53.541228,↵ "lng" : -2.1114828↵ },↵ "southwest" : {↵ "lat" : 53.5406464,↵ "lng" : -2.1120657↵ }↵ },↵ "copyrights" : "Map data ©2017 Google",↵ "legs" : [↵ {↵ "distance" : {↵ "text" : "0.1 km",↵ "value" : 114↵ },↵ "duration" : {↵ "text" : "1 min",↵ "value" : 27↵ },↵ "end_address" : "Broseley House, 81 Union St, Oldham OL1 1PF, UK",↵ "end_location" : {↵ "lat" : 53.5406464,↵ "lng" : -2.1120657↵ },↵ "start_address" : "Ashton Arms, Oldham, UK",↵ "start_location" : {↵ "lat" : 53.5411291,↵ "lng" : -2.1114828↵ },↵ "steps" : [↵ {↵ "distance" : {↵ "text" : "41 m",↵ "value" : 41↵ },↵ "duration" : {↵ "text" : "1 min",↵ "value" : 7↵ },↵ "end_location" : {↵ "lat" : 53.54116,↵ "lng" : -2.1119794↵ },↵ "html_instructions" : "Head \u003cb\u003enorthwest\u003c/b\u003e on \u003cb\u003eClegg St\u003c/b\u003e toward \u003cb\u003eAscroft St\u003c/b\u003e",↵ "polyline" : {↵ "points" : "agxeIvk{KIDEDADAF?H#JJr#"↵ },↵ "start_location" : {↵ "lat" : 53.5411291,↵ "lng" : -2.1114828↵ },↵ "travel_mode" : "DRIVING"↵ },↵ {↵ "distance" : {↵ "text" : "52 m",↵ "value" : 52↵ },↵ "duration" : {↵ "text" : "1 min",↵ "value" : 11↵ },↵ "end_location" : {↵ "lat" : 53.5407078,↵ "lng" : -2.1117626↵ },↵ "html_instructions" : "Turn \u003cb\u003eleft\u003c/b\u003e onto \u003cb\u003eHarrison St\u003c/b\u003e",↵ "maneuver" : "turn-left",↵ "polyline" : {↵ "points" : "ggxeIzn{KxAk#"↵ },↵ "start_location" : {↵ "lat" : 53.54116,↵ "lng" : -2.1119794↵ },↵ "travel_mode" : "DRIVING"↵ },↵ {↵ "distance" : {↵ "text" : "21 m",↵ "value" : 21↵ },↵ "duration" : {↵ "text" : "1 min",↵ "value" : 9↵ },↵ "end_location" : {↵ "lat" : 53.5406464,↵ "lng" : -2.1120657↵ },↵ "html_instructions" : "Turn \u003cb\u003eright\u003c/b\u003e onto \u003cb\u003ePrinter St\u003c/b\u003e",↵ "maneuver" : "turn-right",↵ "polyline" : {↵ "points" : "mdxeInm{KJ|#"↵ },↵ "start_location" : {↵ "lat" : 53.5407078,↵ "lng" : -2.1117626↵ },↵ "travel_mode" : "DRIVING"↵ }↵ ],↵ "traffic_speed_entry" : [],↵ "via_waypoint" : []↵ }↵ ],↵ "overview_polyline" : {↵ "points" : "agxeIvk{KOJCL#TJr#xAk#J|#"↵ },↵ "summary" : "Ascroft St and Harrison St",↵ "warnings" : [],↵ "waypoint_order" : []↵ }↵ ],↵ "status" : "OK"↵}↵"__proto__: Objectconstructor: function Object()hasOwnProperty: function hasOwnProperty()isPrototypeOf: function isPrototypeOf()propertyIsEnumerable: function propertyIsEnumerable()toLocaleString: function toLocaleString()toString: function toString()valueOf: function valueOf()__defineGetter__: function __defineGetter__()__defineSetter__: function __defineSetter__()__lookupGetter__: function __lookupGetter__()__lookupSetter__: function __lookupSetter__()get __proto__: function __proto__()set __proto__: function __proto__()

Please check below thing it may help you. In JSON response you are passing data key with response so on ajax part you have to use data.data.routes to get proper output.
function getGoogle() {
$lat = Input::get('lat');
$lng = Input::get('lng');
$destinationLat = Input::get('destinationLat');
$destinationLng = Input::get('destinationLng');
$google = file_get_contents('https://maps.googleapis.com/maps/api/directions/json?origin=' . $lat . ',' . $lng . '&destination=' . $destinationLat . ',' . $destinationLng . '&key=AIzaSyAirYgs4Xnt9QabG9v56jsIcCNfNZazq50');
return response()->json(['data' => json_decode($google)]);
// Google's response by default is in JSON, so I've converted to array `json_decode($google)`.
}
//Here is the json response you get from ajax success.
var json = {
"geocoded_waypoints": [
{
"geocoder_status": "OK",
"place_id": "ChIJuVnJ34G3e0gRW_oSYLOUxEc",
"types": [
"premise"
]
},
{
"geocoder_status": "OK",
"place_id": "ChIJ0afvWH-3e0gRehrvBJAsflw",
"types": [
"premise"
]
}
],
"routes": [
{
"bounds": {
"northeast": {
"lat": 53.541228,
"lng": -2.1114936
},
"southwest": {
"lat": 53.5406464,
"lng": -2.1120657
}
},
"copyrights": "Dane do Mapy ©2017 Google",
"legs": [
{
"distance": {
"text": "0,1 km",
"value": 112
},
"duration": {
"text": "1 min",
"value": 27
},
"end_address": "Broseley House, 81 Union St, Oldham OL1 1PF, Wielka Brytania",
"end_location": {
"lat": 53.5406464,
"lng": -2.1120657
},
"start_address": "Ashton Arms, Oldham, Wielka Brytania",
"start_location": {
"lat": 53.5411486,
"lng": -2.1114936
},
"steps": [
{
"distance": {
"text": "39 m",
"value": 39
},
"duration": {
"text": "1 min",
"value": 7
},
"end_location": {
"lat": 53.54116,
"lng": -2.1119794
},
"html_instructions": "Kieruj się <b>Clegg St</b> na <b>północny zachód</b> w stronę <b>Ascroft St</b>",
"polyline": {
"points": "egxeIxk{KEBEDADAF?H#JJr#"
},
"start_location": {
"lat": 53.5411486,
"lng": -2.1114936
},
"travel_mode": "DRIVING"
},
{
"distance": {
"text": "52 m",
"value": 52
},
"duration": {
"text": "1 min",
"value": 11
},
"end_location": {
"lat": 53.5407078,
"lng": -2.1117626
},
"html_instructions": "Skręć <b>w lewo</b> w <b>Harrison St</b>",
"maneuver": "turn-left",
"polyline": {
"points": "ggxeIzn{KxAk#"
},
"start_location": {
"lat": 53.54116,
"lng": -2.1119794
},
"travel_mode": "DRIVING"
},
{
"distance": {
"text": "21 m",
"value": 21
},
"duration": {
"text": "1 min",
"value": 9
},
"end_location": {
"lat": 53.5406464,
"lng": -2.1120657
},
"html_instructions": "Skręć <b>w prawo</b> w <b>Printer St</b>",
"maneuver": "turn-right",
"polyline": {
"points": "mdxeInm{KJ|#"
},
"start_location": {
"lat": 53.5407078,
"lng": -2.1117626
},
"travel_mode": "DRIVING"
}
],
"traffic_speed_entry": [],
"via_waypoint": []
}
],
"overview_polyline": {
"points": "egxeIxk{KKHCL#TJr#xAk#J|#"
},
"summary": "Ascroft St i Harrison St",
"warnings": [],
"waypoint_order": []
}
],
"status": "OK"
};
for(var jsonvalue in json.routes){
var legs = json.routes[jsonvalue].legs;
if(legs.length){
for(var legvalue in legs){
$("ul").append("<li>Distance : " + legs[legvalue].distance.text + " -- Duration : " +legs[legvalue].duration.text + " </li>")
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul>
</ul>

Assuming you have an Object {} (and not just a string of text) you should be able to do
console.log(Object.routes)

I think in success promise you aren't getting proper data format how you are expecting put a debug point on console.log in success promise and check the structure of the object and select the routes.
`success: function(data) {
console.log(data.routes);
}`

You can get a formatted stripped-down output with:
var formatted = JSON.stringify(data,
function(key, value) {
// remove geocoded_waypoints
if (key == "geocoded_waypoints") return;
// remove other branches...
return value;},
2);
... or just only return the few keys you need.
Source: W3C

just parse your response:
var res=JSON.parse(response);

Related

How remove data from an array in aggrigation whithout disturbing outside data in mongodb

Here I am trying to get entire data but if date less then current then do not fetch that date from the database.
{
"_id" : ObjectId("5d6fad0f9e0dc027fc6b5ab5"),
"highlights" : [
"highlights-1",
],
"notes" : [
"Listen"
],
"soldout" : false,
"active" : false,
"operator" : ObjectId(""),
"title" : "2D1N Awesome trip to Knowhere 99",
"destinations" : [
{
"coordinatesType" : "Point",
"_id" : ObjectId("5d6fad0f9e0dc027fc6b5ab6"),
}
],
"difficulty" : "Easy",
"duration" : {
"_id" : ObjectId("5d6fad0f9e0dc027fc6b5ab7"),
"days" : NumberInt(2),
"nights" : NumberInt(1)
},
"media" : {
"_id" : ObjectId("5d6fad0f9e0dc027fc6b5ab8"),
"images" : [
],
"videos" : [
]
},
"description" : "Surrounded ",
"inclusions" : [
{
"_id" : ObjectId(""),
"text" : "Included"
}
],
"itinerary" : "Surrounded .",
"thingsToCarry" : [
{
"_id" : ObjectId(""),
"text" : "Yourself"
}
],
"exclusions" : [
{
"_id" : ObjectId(""),
"text" : "A Lot"
}
],
"policy" : "Fully refundable 7777 Days before the date of Experience",
"departures" : [
{
"dates" : [
ISODate("2019-11-19T02:44:58.989+0000"),
ISODate("2019-11-23T17:19:47.878+0000")
],
"_id" : ObjectId(""),
"bookingCloses" : "2 Hours Before",
"maximumSeats" : NumberInt(20),
"source" : {
"coordinatesType" : "Point",
"_id" : ObjectId("5d6fad0f9e0dc027fc6b5ac2"),
"code" : "code",
"name" : "Manali",
"state" : "Himachal Pradesh",
"region" : "North",
"country" : "India",
"coordinates" : [
23.33,
NumberInt(43),
NumberInt(33)
]
},
"pickupPoints" : [
{
"coordinatesType" : "Point",
"_id" : ObjectId("5d6fad0f9e0dc027fc6b5ac3"),
"name" : "name-3",
"address" : "address-3",
"time" : "time-3",
"coordinates" : [
23.33,
NumberInt(43),
NumberInt(33)
]
}
],
"prices" : {
"3" : NumberInt(5)
},
"mrps" : {
"3" : NumberInt(5)
},
"markup" : NumberInt(25),
"discount" : NumberInt(0),
"b2m" : {
"3" : NumberInt(5)
},
"m2c" : {
"3" : 6.25
},
"minimumOccupancy" : NumberInt(3),
"maximumOccupancy" : NumberInt(3)
}
],
"bulkDiscounts" : [
{
"_id" : ObjectId("5d6fad0f9e0dc027fc6b5ac4")
}
],
}
In this I am trying to get all the data except the date section should be different. Means I should get my output as below
{
"_id": "5d6fad0f9e0dc027fc6b5ab5",
"highlights": [
"highlights-1",
"highlights-2",
"highlights-3",
"highlights-4",
"highlights-5"
],
"notes": [
"Listen"
],
"soldout": false,
"active": false,
"operator": "5d5d84e8c89fbf00063095f6",
"title": "2D1N Awesome trip to Knowhere 99",
"destinations": [
{
"code": "code",
"name": "Manali",
"coordinates": [
23.33,
43,
33
]
}
],
"difficulty": "Easy",
"duration": {
"_id": "5d6fad0f9e0dc027fc6b5ab7",
"days": 2,
"nights": 1
},
"media": {
"_id": "5d6fad0f9e0dc027fc6b5ab8",
"images": [
],
"videos": []
},
"description": "Surrounded.",
"inclusions": [
{
"_id": "5d6fad0f9e0dc027fc6b5abe",
"text": "Included"
}
],
"itinerary": "Surrounded",
"thingsToCarry": [
{
"_id": "5d6fad0f9e0dc027fc6b5abf",
"text": "Yourself"
}
],
"exclusions": [
{
"_id": "5d6fad0f9e0dc027fc6b5ac0",
"text": "A Lot"
}
],
"policy": "Fully refundable 7777 Days before the date of Experience",
"departures": [
{
"dates": [
"2019-11-23T17:19:47.878Z"
],
"_id": "5d6fad0f9e0dc027fc6b5ac1",
"bookingCloses": "2 Hours Before",
"maximumSeats": 20,
"source": {
"code": "code",
"name": "Manali",
"coordinates": [
23.33,
43,
33
]
},
"pickupPoints": [
{
"coordinatesType": "Point",
"_id": "5d6fad0f9e0dc027fc6b5ac3",
"name": "name-3",
"address": "address-3",
"time": "time-3",
"coordinates": [
23.33,
43,
33
]
}
],
"mrps": {
"3": 5
},
"markup": 25,
"discount": 0,
"b2m": {
"3": 5
},
"m2c": {
"3": 6.25
},
"minimumOccupancy": 3,
"maximumOccupancy": 3
}
],
"bulkDiscounts": [
{
"_id": "5d6fad0f9e0dc027fc6b5ac4"
}
],
"url": "",
}
]
I mean to say that no difference in output except dates array. If dates are less than current date then no need to fetch else fetch from DB with filtered dates array.
If you use mongo 3.4> then you can try with $addFields and $filter:
myCollection.aggregate([
{$match: {
'departures.dates': {
$elemMatch: {$gt: new Date()}}
}
},
{$addFields: {
'departures.dates': {
$filter: {
input: '$departures.dates',
as: 'date',
cond: {
$gt: ['$$date', new Date()]
}
}
}
}}
])
I was missing one terms here that my documnet structure is like below
{
_id: ObjecId(),
departure: [{
dates: [Array]
}]
}
So, here is my solution in the below code
pipeline = [
{ $unwind: '$departures' },
{
$addFields: {
'departures.dates': {
$filter: {
input: '$departures.dates',
as: 'date',
cond: {
$gt: ['$$date', new Date()]
}
}
}
}
}
];

TypeError: Cannot read property '0' of undefined while accessing "photo_reference" property

Below is the JSON i get from the google places API. Parsing the Json with JSON.parse(body). The "results" key is an array of Objects that i am looping through to access the property of photos. Hope the code is clearer now. I have pasted in the valid JSON that i am getting from the api call.
{
"html_attributions" : [],
"next_page_token" : "CqQCGwEAAI5PpCTJI6Qoa1CD9iA4EpJha6t0gMlZ3I3DpOIVgE1BUYh5NNI0lXRuvAltI8RhOilTNJggXsR3TEP2C6hoIsibEWZXnZClbEcZzes7LGqJuQ0heJWipe7RNbxq8S8zuao1HWfECs11i44WO0Luv-4bYx5GlCEj6Wl07LitkzwG4u0e4FyIHogyaShky5Awd44ZyOcqKzy7wYBr7p37j6A6PMdR7zn7cMWQKiVolfHQbFZerVJ3JJ5MiKSshocG189wPKjqJzSACE6W19LmZ7TIMB9qm7jQANNQStrsq7rYAWIBQ-UqJ_6Hv9jv1xL7eRQ9bkyR17u7xPZWfeCU69u_PQmGvuvSWNJDvNUuoI-uwLc_RhgTZp26kyzMlXwYHRIQXy13ridwzgvlBU8ez_y-WBoUcBN7UvN8Q8iuDyS_LjXEWmT_sIk",
"results" : [
{
"geometry" : {
"location" : {
"lat" : 28.615572,
"lng" : 77.3468
},
"viewport" : {
"northeast" : {
"lat" : 28.6169209802915,
"lng" : 77.34814898029151
},
"southwest" : {
"lat" : 28.6142230197085,
"lng" : 77.34545101970849
}
}
},
"icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png",
"id" : "dea8496f678dc1f01381a85298e37a0905a3ca11",
"name" : "Malabar Junction Restaurant",
"opening_hours" : {
"open_now" : true,
"weekday_text" : []
},
"photos" : [
{
"height" : 746,
"html_attributions" : [
"\u003ca href=\"https://maps.google.com/maps/contrib/117230637789134827076/photos\"\u003eSwati\u003c/a\u003e"
],
"photo_reference" : "CmRaAAAArbpjr1fjNp2Fc4ww8Vkgrzzzt5aHEvACzEZFa-XCJU3Fw2JqFLSDo64jlFWwDZwdYaFP_cIgdqI37TJ25mVB2W_rtoTv_aI0LJGgnh_P4-UF7u45ZvqdM-bE4ljYD2yyEhDjv-4AWC5AKcE713GL1qAsGhQjAN2oS1KWv52f8XsjEK3Pmnv53w",
"width" : 750
}
],
"place_id" : "ChIJx6qqqj3lDDkRcBw22oTfWgk",
"reference" : "CmRRAAAAZBpNfAiO2G_y57bLoFTSM28MG4xUi-VAg3kJgV2ZzksdhpzySwxdPNdPP1paEIE46i70oxgLHliUcEjxalukNEyhN85J-ryRbXVVMkg4Tz-MGBGhgVur7SV5b4IFePnfEhABXu9pHswL4Up5w-k9td94GhSDs13DRQVxPOpI8iWqUbLyd_WJUg",
"scope" : "GOOGLE",
"types" : [ "restaurant", "food", "point_of_interest", "establishment" ],
"vicinity" : "62, 8, Rani Jhansi Marg, Block 10, Sector 10, Noida"
}
],
"status" : "OK"
}
Trying to Access the photo_reference property like so
let resultJSON = JSON.parse(body);
let results = resultJSON["results"];
for (var i = 0; i < results.length; i++) {
let name = results[i]["name"];
console.log(results[i].photos[0].photo_reference);
}
Here is a snippet that shows your updated code is working.
let resultJSON = {
"html_attributions": [],
"next_page_token": "CqQCGwEAAI5PpCTJI6Qoa1CD9iA4EpJha6t0gMlZ3I3DpOIVgE1BUYh5NNI0lXRuvAltI8RhOilTNJggXsR3TEP2C6hoIsibEWZXnZClbEcZzes7LGqJuQ0heJWipe7RNbxq8S8zuao1HWfECs11i44WO0Luv-4bYx5GlCEj6Wl07LitkzwG4u0e4FyIHogyaShky5Awd44ZyOcqKzy7wYBr7p37j6A6PMdR7zn7cMWQKiVolfHQbFZerVJ3JJ5MiKSshocG189wPKjqJzSACE6W19LmZ7TIMB9qm7jQANNQStrsq7rYAWIBQ-UqJ_6Hv9jv1xL7eRQ9bkyR17u7xPZWfeCU69u_PQmGvuvSWNJDvNUuoI-uwLc_RhgTZp26kyzMlXwYHRIQXy13ridwzgvlBU8ez_y-WBoUcBN7UvN8Q8iuDyS_LjXEWmT_sIk",
"results": [{
"geometry": {
"location": {
"lat": 28.615572,
"lng": 77.3468
},
"viewport": {
"northeast": {
"lat": 28.6169209802915,
"lng": 77.34814898029151
},
"southwest": {
"lat": 28.6142230197085,
"lng": 77.34545101970849
}
}
},
"icon": "https://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png",
"id": "dea8496f678dc1f01381a85298e37a0905a3ca11",
"name": "Malabar Junction Restaurant",
"opening_hours": {
"open_now": true,
"weekday_text": []
},
"photos": [{
"height": 746,
"html_attributions": [
"\u003ca href=\"https://maps.google.com/maps/contrib/117230637789134827076/photos\"\u003eSwati\u003c/a\u003e"
],
"photo_reference": "CmRaAAAArbpjr1fjNp2Fc4ww8Vkgrzzzt5aHEvACzEZFa-XCJU3Fw2JqFLSDo64jlFWwDZwdYaFP_cIgdqI37TJ25mVB2W_rtoTv_aI0LJGgnh_P4-UF7u45ZvqdM-bE4ljYD2yyEhDjv-4AWC5AKcE713GL1qAsGhQjAN2oS1KWv52f8XsjEK3Pmnv53w",
"width": 750
}],
"place_id": "ChIJx6qqqj3lDDkRcBw22oTfWgk",
"reference": "CmRRAAAAZBpNfAiO2G_y57bLoFTSM28MG4xUi-VAg3kJgV2ZzksdhpzySwxdPNdPP1paEIE46i70oxgLHliUcEjxalukNEyhN85J-ryRbXVVMkg4Tz-MGBGhgVur7SV5b4IFePnfEhABXu9pHswL4Up5w-k9td94GhSDs13DRQVxPOpI8iWqUbLyd_WJUg",
"scope": "GOOGLE",
"types": ["restaurant", "food", "point_of_interest", "establishment"],
"vicinity": "62, 8, Rani Jhansi Marg, Block 10, Sector 10, Noida"
}],
"status": "OK"
}
let results = resultJSON["results"];
for (var i = 0; i < results.length; i++) {
let name = results[i]["name"];
console.log(results[i].photos[0].photo_reference);
}

Javascript - Finding in subarray by value from another array

I have two javascript objects:
var classroom = {
"number" : "1",
"student" : [
{
"number" : 1,
"items" : [
{
"key" : "00000000000000000000001C",
"date" : "2016-04-21T17:35:39.997Z"
}
]
},
{
"number" : 2,
"items" : [
{
"key" : "00000000000000000000001D",
"date" :"2016-04-21T17:35:39.812Z"
},
{
"key" : "00000000000000000000002N",
"date" :"2016-04-21T17:35:40.159Z"
},
{
"key" : "00000000000000000000002Ñ",
"date" :"2016-04-21T17:35:42.619Z"
}
]
}
],
}
AND
var items = [
{
"fields" : {
"tags" : [
{
"key" : "00000000000000000000001C",
"Batch" : "50",
"Bin" : "01",
"Tray" : "02"
},
{
"key" : "00000000000000000000002N",
"Batch" : "55",
"Bin" : "05",
"Tray" : "12"
},
{
"key" : "000000000000228510000032",
"Batch" : "12",
"Bin" : "12",
"Tray" : "01"
}
],
"Name" : "Rubber"
},
"_id" : "56d19b48faa37118109977c0"
},
{
"fields" : {
"tags" : [
{
"key" : "00000000000000000000001D",
"Batch" : "50",
"Bin" : "01",
"Tray" : "05"
},
{
"key" : "00000000000000000000002Ñ",
"Batch" : "52",
"Bin" : "07",
"Tray" : "02"
},
{
"key" : "221567010000000000000089",
"Batch" : "11",
"Bin" : "15",
"Tray" : "03"
}
],
"Name" : "Book"
},
"_id" : "56d19b48faa37118109977c1"
}
];
Ok, I need to create a function that goes through every item of every student in classroom variable. With each item, I need to find in the items array the object that has the exact same key in one of its tags.
My code is getting strange results...missmatching items...
var finalitems = [];
classroom.student.forEach( function (student){
student.items.forEach( function (obj){
items.forEach( function (theitem){
theitem.fields.tags.forEach( function (tag){
if (tag.key === obj.key) {
var newitem = theitem;
newitem.tag = obj;
finalitems.push(newitem);
}
});
});
});
});
I know that foreach is a kind of a pointer but I don't really understand why it is working strange and how it should be done.
Regards,
javascript variables only save object references, not the actual object in memory, so this line:
var newitem = theitem;
means newitem refers to the same object as theitem, NOT create a new object from theitem.
so
newitem.tag = obj;
is the same as
theitem.tag = obj;
Which means you're modifying the input objects, that's why you won't get the expected output.
To get the desired behavior you need to create a copy of theitem and assign that object to newitem variable:
var newitem = Object.create(theitem);
Maybe this helps with a lot more iterations.
var classroom = { "number": "1", "student": [{ "number": 1, "items": [{ "key": "00000000000000000000001C", "date": "2016-04-21T17:35:39.997Z" }] }, { "number": 2, "items": [{ "key": "00000000000000000000001D", "date": "2016-04-21T17:35:39.812Z" }, { "key": "00000000000000000000002N", "date": "2016-04-21T17:35:40.159Z" }, { "key": "00000000000000000000002Ñ", "date": "2016-04-21T17:35:42.619Z" }] }] },
items = [{ "fields": { "tags": [{ "key": "00000000000000000000001C", "Batch": "50", "Bin": "01", "Tray": "02" }, { "key": "00000000000000000000002N", "Batch": "55", "Bin": "05", "Tray": "12" }, { "key": "000000000000228510000032", "Batch": "12", "Bin": "12", "Tray": "01" }], "Name": "Rubber" }, "_id": "56d19b48faa37118109977c0" }, { "fields": { "tags": [{ "key": "00000000000000000000001D", "Batch": "50", "Bin": "01", "Tray": "05" }, { "key": "00000000000000000000002Ñ", "Batch": "52", "Bin": "07", "Tray": "02" }, { "key": "221567010000000000000089", "Batch": "11", "Bin": "15", "Tray": "03" }], "Name": "Book" }, "_id": "56d19b48faa37118109977c1" }],
finalitems = [];
classroom.student.forEach(function (student) {
student.items.forEach(function (studentItem) {
items.forEach(function (item) {
item.fields.tags.forEach(function (itemTag) {
if (itemTag.key === studentItem.key) {
finalitems.push({
key: studentItem.key,
date: studentItem.date,
Batch: itemTag.Batch,
Bin: itemTag.Bin,
Tray: itemTag.Tray,
});
}
});
});
});
});
document.write('<pre>' + JSON.stringify(finalitems, 0, 4) + '</pre>');

Iterate through JSON from MapQuest API

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.

How to use if statement inside JSON?

How to use if statement inside JSON Here is the code:
.......................................................................................
var config =
[
{
"name" : "SiteTitle",
"bgcolor" : "",
"color" : "",
"position" : "TL",
"text" : "step1",
"time" : 5000
},
{
"name" : "Jawal",
"bgcolor" : "",
"color" : "",
"text" : "step2",
"position" : "BL",
"time" : 5000
},
{
"name" : "Password",
"bgcolor" : "",
"color" : "",
"text" : "step3",
"position" : "TL",
"time" : 5000
}
],
//define if steps should change automatically
autoplay = false,
//timeout for the step
showtime,
//current step of the tour
step = 0,
//total number of steps
total_steps = config.length;
This is the required result something like this:
var config =
[
if(page==true) {
{
"name" : "SiteTitle",
"bgcolor" : "",
"color" : "",
"position" : "TL",
"text" : "step1",
"time" : 5000
},
{
"name" : "Jawal",
"bgcolor" : "",
"color" : "",
"text" : "step2",
"position" : "BL",
"time" : 5000
}
} else {
{
"name" : "Password",
"bgcolor" : "",
"color" : "",
"text" : "step3",
"position" : "TL",
"time" : 5000
}
}
],
//define if steps should change automatically
autoplay = false,
//timeout for the step
showtime,
//current step of the tour
step = 0,
//total number of steps
total_steps = config.length;
Actually this way is wrong and makes a JavaScript syntax error.
Validating the JSON Schema Draft-07, JSON now supports the if...then...else keywords for conditional data representation.
Here is a quick example:
{
"type": "integer",
"minimum": 1,
"maximum": 1000,
"if": { "minimum": 100 },
"then": { "multipleOf": 100 },
"else": {
"if": { "minimum": 10 },
"then": { "multipleOf": 10 }
}
}
Edits
Using the OP's example in the context, it can be written like this:
{
"if": {
"page": true
},
"then": [
{
"name": "SiteTitle",
"bgcolor": "",
"color": "",
"position": "TL",
"text": "step1",
"time": 5000
},
{
"name": "Jawal",
"bgcolor": "",
"color": "",
"text": "step2",
"position": "BL",
"time": 5000
}
],
"else": [
{
"name": "Password",
"bgcolor": "",
"color": "",
"text": "step3",
"position": "TL",
"time": 5000
}
]
}
That's regular JavaScript, not JSON. Move the if statement outside:
if (page) {
var config = [
{
"name" : "SiteTitle",
"bgcolor" : "",
"color" : "",
"position" : "TL",
"text" : "step1",
"time" : 5000
}, {
"name" : "Jawal",
"bgcolor" : "",
"color" : "",
"text" : "step2",
"position" : "BL",
"time" : 5000
}
];
} else {
var config = [
{
"name" : "Password",
"bgcolor" : "",
"color" : "",
"text" : "step3",
"position" : "TL",
"time" : 5000
}
];
}
you can add an if inside JSON.
const config = [
...(page ? [
{
"name" : "SiteTitle",
"bgcolor" : "",
"color" : "",
"position" : "TL",
"text" : "step1",
"time" : 5000
},
{
"name" : "Jawal",
"bgcolor" : "",
"color" : "",
"text" : "step2",
"position" : "BL",
"time" : 5000
}] : [{
"name" : "Password",
"bgcolor" : "",
"color" : "",
"text" : "step3",
"position" : "TL",
"time" : 5000
}]),
];
or perhaps this:
var config =
(page == true) ?
[
{
"name" : "SiteTitle",
"bgcolor" : "",
"color" : "",
"position" : "TL",
"text" : "step1",
"time" : 5000
},
{
"name" : "Jawal",
"bgcolor" : "",
"color" : "",
"text" : "step2",
"position" : "BL",
"time" : 5000
}
:
{
"name" : "Password",
"bgcolor" : "",
"color" : "",
"text" : "step3",
"position" : "TL",
"time" : 5000
}
];
You can do it this way also (not saying this is the best way but it's another way and could be useful in some scenarios)
let config = [];
if (page) {
config.push({
"name" : "SiteTitle",
"bgcolor" : "",
"color" : "",
"position" : "TL",
"text" : "step1",
"time" : 5000
});
config.push({
"name" : "Jawal",
"bgcolor" : "",
"color" : "",
"text" : "step2",
"position" : "BL",
"time" : 5000
});
} else {
config.push({
"name" : "Password",
"bgcolor" : "",
"color" : "",
"text" : "step3",
"position" : "TL",
"time" : 5000
});
}
You can use a library jsoncode that allows you to apply logical expressions directly into JSON and get the necessary result according to the transmitted model:
import jsoncode from './jsoncode.lib.mjs';
const json_src = {
"configs [AS ARRAY]": {
"[...IF page]": [
{
"name": "SiteTitle",
"bgcolor": "",
"color": "",
"position": "TL",
"text": "step1",
"time": 5000
}, {
"name": "Jawal",
"bgcolor": "",
"color": "",
"text": "step2",
"position": "BL",
"time": 5000
}
],
"[IF !page]": {
"name": "Password",
"bgcolor": "",
"color": "",
"text": "step3",
"position": "TL",
"time": 5000
}
}
};
const configsA = jsoncode(json_src, { page: true }).configs;
const configsB = jsoncode(json_src, { page: false }).configs;
console.log('configsA:', configsA);
console.log('configsB:', configsB);
https://www.npmjs.com/package/jsoncode

Categories