Related
I have an array of objects that is indexed and I want to iterate through it to convert it to a new flat array.
This is the array of objects:
"attentionSchedules": [
{
"room": "1",
"schedules": [
{
"days": [
"SA",
"WE"
],
"_id": "6271xxxx",
"initialTimeStr": "12:00 am",
"finalTimeStr": "12:00 am",
"initialTime": "2022-05-03T06:00:00.000Z",
"finalTime": "2022-05-03T06:00:00.000Z"
}
],
"place": {
"loc": {
"type": "Point",
"coordinates": [
-88.03xxx,
15.49xxx
]
},
"_idPlace": "5d5ba845xxx",
"name": "Labs",
"address": "xxx"
},
"floor": 1
},
{
"room": "23",
"floor": 1,
"schedules": [
{
"days": [
"MO",
"TH",
"WE",
"YOU",
"FR",
"SA"
],
"_id": "62754264a627af5fc44286b3",
"initialTimeStr": "08:00 am",
"finalTimeStr": "09:00 pm",
"initialTime": "2022-05-06T14:00:00.000Z",
"finalTime": "2022-05-07T03:00:00.000Z"
}
],
"place": {
"loc": {
"type": "Point",
"coordinates": [
-88.02xxx,
15.50xxx
]
},
"_idPlace": "ba",
"name": "Labs",
"address": "xx"
}
}
],
I want to iterate over it, get its values and convert it to a new object like this:
{
lng: -88.02xxx
lat: 15.50xxx
_idPlace: "ba"
}
.
.
.
N
How can I do this? I'm using angular, I'm doing the method with javascript/types Currently I did something like this:
let locCoord: any[] = [];
this.attentionSchedules?.forEach(elm => {
for (const [key, value] of Object.entries(elm.place.loc)) {
let lng = value[0];
let lat = value[1];
let dataObjLoc = {
_id: elm.place._id,
lat: lat,
lng: lng
}
locCoord.push(dataObjLoc);
}
});
console.log(locCoord);
And it returns the following:
[
{
"_idPlace": "5d5ba84531f75411f3b6417e",
"lat": "or",
"lng": "P"
},
{
"_idPlace": "5d5ba84531f75411f3b6417e",
"lat": 15.4997741,
"lng": -88.03860120000002
},
{
"_idPlace": "6109766f913cf469f6b177ba",
"lat": "or",
"lng": "P"
},
{
"_idPlace": "6109766f913cf469f6b177ba",
lat: 15.5085874,
"lng": -88.0264096
}
]
It is not what I need, since when using Object.entries it not only extracts the values but also duplicates the keys. Somebody could help me? Please
I'm not sure you need to loop over Object.entries(elm.place.loc) (if I've understood the problem). I think you can just extract the values somewhat directly:
const attentionSchedules = [{"room":"1","schedules":[{"days":["SA","WE"],"_id":"6271xxxx","initialTimeStr":"12:00 am","finalTimeStr":"12:00 am","initialTime":"2022-05-03T06:00:00.000Z","finalTime":"2022-05-03T06:00:00.000Z"}],"place":{"loc":{"type":"Point","coordinates":[-88.03,15.49]},"_idPlace":"5d5ba845xxx","name":"Labs","address":"xxx"},"floor":1},{"room":"23","floor":1,"schedules":[{"days":["MO","TH","WE","YOU","FR","SA"],"_id":"62754264a627af5fc44286b3","initialTimeStr":"08:00 am","finalTimeStr":"09:00 pm","initialTime":"2022-05-06T14:00:00.000Z","finalTime":"2022-05-07T03:00:00.000Z"}],"place":{"loc":{"type":"Point","coordinates":[-88.02,15.5]},"_idPlace":"ba","name":"Labs","address":"xx"}}];
let locCoord = [];
attentionSchedules?.forEach(({ place }) => {
const [lng, lat] = place.loc.coordinates;
locCoord.push({
_id: place._idPlace,
lat: lat,
lng: lng
});
});
console.log(locCoord);
I am trying banging my head to filter json written below to get desired result.
[{
"Key": "EShSOKthupE=",
"ImageUrl": "path",
"Title": "ABC",
"CityId": 16,
"TimezoneShortName": "PYT",
"UtcHrsDiff": 8.5,
"PlaceKey": "QIZHdWOa77o=",
"PlaceName": "Shymala Hills Slums",
"Lat": 23.2424856,
"Long": 77.39488289999997,
"ActivityList": [ "Test Activity" ]
},
{
"Key": "NXLQpZAZT4M=",
"ImageUrl": "",
"Title": "ASAS",
"CityId": 17,
"TimezoneShortName": "AEST",
"UtcHrsDiff": 10,
"PlaceKey": "o4fAkahBzYY=",
"PlaceName": "ASAS",
"Lat": 12.9856503,
"Long": 77.60569269999996,
"ActivityList": [ "Adventure Sport" ]
}]
Now I want to get json like this from above json using lodash or undescore js.
[{
"PlaceKey": "QIZHdWOa77o=",
"PlaceName": "ABC",
"Lat": 23.2424856,
"Long": 77.39488289999997
},
{
"PlaceKey": "o4fAkahBzYY=",
"PlaceName": "ASAS",
"Lat": 12.9856503,
"Long": 77.60569269999996,
}]
Any help I can get on this?
Using lodash:
_.map(yourArray, (el => _.pick(el, ['PlaceKey', 'PlaceName', 'Lat', 'Long'])))
You can do this simply in Javascript, without the need of any external library like :
filteredArray=arr.map(function(item){
return {
"PlaceKey": item.PlaceKey,
"PlaceName": item.PlaceName,
"Lat": item.Lat,
"Long": item.Long,
}
})
use _.map function
var finalArray = _.map(your_arr, function(obj) {
return {
"PlaceKey": obj.PlaceKey,
"PlaceName": obj.PlaceName,
"Lat": obj.Lat,
"Long": obj.Long,
}
});
or just use the arrays map function:
var finalArray = your_arr.map(function(obj) {
return {
"PlaceKey": obj.PlaceKey,
"PlaceName": obj.PlaceName,
"Lat": obj.Lat,
"Long": obj.Long,
}
});
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.
I'm getting this JSON file. The path arrays can be from 1 to 100,
{
"waypoints": [
{
"path0": [
{
"color": "#0000FF"
},
{
"lat": "37.9875000",
"lon": "23.7609260"
},
{
"lat": "37.9873130",
"lon": "23.7607460"
},
{
"lat": "37.9873840",
"lon": "23.7604100"
}
],
"path1": [
{
"color": "#00FF00"
},
{
"lat": "37.9873840",
"lon": "23.7604100"
},
{
"lat": "37.9878040",
"lon": "23.7605670"
},
{
"lat": "37.9882590",
"lon": "23.7607340"
}
],
"path2": [
{
"color": "#FF0000"
},
{
"lat": "37.9882590",
"lon": "23.7607340"
},
{
"lat": "37.9884690",
"lon": "23.7598760"
}
]
}
]
}
How can i see how many path(path0, path1, ..) arrays do i have inside waypoints in Javascript?
Using obj.waypoints.length returns 0.
Thank you.
On a modern browser you can use Object.keys :
var nbpaths = Object.keys(obj.waypoints[0]).length;
For compatibility with ie8, you can count like this :
var nbpaths = 0;
for (var key in obj.waypoints[0]) nbpaths++;
I'm trying to get json response from google maps using this code:
var address = 'Sydney,NSW';
$.ajax({
type: "GET",
url: "http://maps.googleapis.com/maps/api/geocode/json?sensor=false",
dataType: "jsonp",
data: ({"address":address}),
success: function(json){
if (json.status == "OK") {
alert(":)");
} else {
alert('wrong!');
}
}
});
It's working really good, but...
as a result i'm getting
Uncaught SyntaxError: Unexpected token :
in Chrome and
Error: no element found in FireFox..
it's seems that something wrong is with returned JSON, but it looking good:
{
"status": "OK",
"results": [ {
"types": [ "locality", "political" ],
"formatted_address": "Sydney New South Wales, Australia",
"address_components": [ {
"long_name": "Sydney",
"short_name": "Sydney",
"types": [ "locality", "political" ]
}, {
"long_name": "New South Wales",
"short_name": "New South Wales",
"types": [ "administrative_area_level_1", "political" ]
}, {
"long_name": "Australia",
"short_name": "AU",
"types": [ "country", "political" ]
} ],
"geometry": {
"location": {
"lat": -33.8689009,
"lng": 151.2070914
},
"location_type": "APPROXIMATE",
"viewport": {
"southwest": {
"lat": -34.1648540,
"lng": 150.6948538
},
"northeast": {
"lat": -33.5719182,
"lng": 151.7193290
}
},
"bounds": {
"southwest": {
"lat": -34.1692489,
"lng": 150.5022290
},
"northeast": {
"lat": -33.4245980,
"lng": 151.3426361
}
}
}
} ]
}
The return must be jsonp not json (the json should be wrapped into a function call)
Try using GM2 (looks like jsonp is not supported in GM3)
$.ajax({
type: "GET",
url: "http://maps.google.com/maps/geo?sensor=false&output=json&"+$.param({"q":address}),
dataType: "jsonp",
success: function(json){
if (json.Status.code == "200") {
alert(":)");
} else {
alert('wrong!');
}
}
});