Related
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);
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
I'm trying to dig into the following array, to turn all of the connector type items into select options when I have parsed it.
At the moment, I can get all the data I require, but I'm wanting to turn each item returned into a single string as opposed to having it return items that have more than one connector type as a single item (beneath example shows what I currently have / desire. That and only show unique types, so if the connector name has been showed once, don't show that name again as an option.
For example (current output):
(Shows duplicates, nested items with more than one type don't break onto single lines)
ConnectorType1
ConnectorType1, ConnectorType2, ConnectorType3
ConnectorType1
ConnectorType1, ConnectorType2
Desired output:
(Shows unique items only, all results broken onto new lines)
ConnectorType1,
ConnectorType2,
ConnectorType3
Pastebin with JSON example:
{
"ChargeDevice": [
{
"ChargeDeviceId": "cfeedcdd5e287bef4b583158a12363f1",
"ChargeDeviceRef": "SRC_LDN60188",
"ChargeDeviceName": "2 Riddons Road",
"ChargeDeviceText": null,
"ChargeDeviceLocation": {
"Latitude": "51.431454",
"Longitude": "0.031175",
"Address": {
"SubBuildingName": null,
"BuildingName": "",
"BuildingNumber": "",
"Thoroughfare": "Riddons Road",
"Street": "Junction with Chinbrook Road",
"DoubleDependantLocality": null,
"DependantLocality": null,
"PostTown": "Leek",
"County": "Greater London",
"PostCode": "SE12 9QR",
"Country": "gb",
"UPRN": null
},
"LocationShortDescription": null,
"LocationLongDescription": ""
},
"ChargeDeviceManufacturer": null,
"ChargeDeviceModel": null,
"PublishStatusID": "1",
"DateCreated": "2014-08-19 05:15:02",
"DateUpdated": "2015-09-02 11:28:16",
"Attribution": "Source London",
"DateDeleted": "n/a",
"Connector": [
{
"ConnectorId": "1",
"ConnectorType": "3-pin Type G (BS1363)",
"RatedOutputkW": "3.7",
"RatedOutputVoltage": "230",
"RatedOutputCurrent": "16",
"ChargeMethod": "Single Phase AC",
"ChargeMode": "1",
"ChargePointStatus": "In service",
"TetheredCable": "0",
"Information": " x 3-pin square (BS 1363) - Standard (up to 3.7kW, 13-16A)",
"Validated": "0"
},
{
"ConnectorId": "2",
"ConnectorType": "Type 2 Mennekes (IEC62196)",
"RatedOutputkW": "7.0",
"RatedOutputVoltage": "230",
"RatedOutputCurrent": "32",
"ChargeMethod": "Single Phase AC",
"ChargeMode": "3",
"ChargePointStatus": "In service",
"TetheredCable": "0",
"Information": " x 7-pin 'Smart' eg Mennekes (IEC 62196) - Fast (7kW, 32A)",
"Validated": "0"
}
],
"DeviceOwner": {
"OrganisationName": "Source London",
"SchemeCode": "SRC_LDN",
"Website": "https://www.sourcelondon.net",
"TelephoneNo": "020 3056 8989"
},
"DeviceController": {
"OrganisationName": "Source London",
"SchemeCode": "SRC_LDN",
"Website": "https://www.sourcelondon.net",
"TelephoneNo": "020 3056 8989"
},
"DeviceAccess": [],
"DeviceNetworks": "Source London",
"ChargeDeviceStatus": "In service",
"PublishStatus": "Published",
"DeviceValidated": "0",
"RecordModerated": "Y",
"RecordLastUpdated": "2015-09-02 11:28:16",
"RecordLastUpdatedBy": "NCR Admin",
"PaymentRequiredFlag": false,
"PaymentDetails": "",
"SubscriptionRequiredFlag": true,
"SubscriptionDetails": "\u00a35 per annum for RFiD card",
"ParkingFeesFlag": false,
"ParkingFeesDetails": "",
"ParkingFeesUrl": null,
"AccessRestrictionFlag": false,
"AccessRestrictionDetails": "",
"PhysicalRestrictionFlag": false,
"PhysicalRestrictionText": "",
"OnStreetFlag": true,
"LocationType": "On-street",
"Bearing": null,
"Accessible24Hours": false
}
]
}
Current code for looping through JSON:
for (let x = 0; x < data.ChargeDevice[i].Connector.length; x++) {
if (connectors.indexOf(data.ChargeDevice[i].Connector[x].ConnectorType) === -1) {
connectors.push(data.ChargeDevice[i].Connector[x].ConnectorType);
$('#connectorList').append(`<option data-loc-name="${connectors}" value="${connectors}">${connectors}</option>`);
}
}
I would suggest you to loop through all connection with Array.from(myJson.ChargeDevice[0].Connector, ....
Then for each connection, you push the value of .ConnectorType into an array (myConnArr) if it is not already present. Like this if(!myConnArr.includes(conn.ConnectorType)) myConnArr.push(conn.ConnectorType)
Lastly, I join all the result and separate them like this .join(", \n").
The full code snippet. For the test purpose, I duplicate some connector value in order to show remove_duplicates() works fine.
let myJson = {
"ChargeDevice": [
{
"ChargeDeviceId": "cfeedcdd5e287bef4b583158a12363f1",
"ChargeDeviceRef": "SRC_LDN60188",
"ChargeDeviceName": "2 Riddons Road",
"ChargeDeviceText": null,
"ChargeDeviceLocation": {
"Latitude": "51.431454",
"Longitude": "0.031175",
"Address": {
"SubBuildingName": null,
"BuildingName": "",
"BuildingNumber": "",
"Thoroughfare": "Riddons Road",
"Street": "Junction with Chinbrook Road",
"DoubleDependantLocality": null,
"DependantLocality": null,
"PostTown": "Leek",
"County": "Greater London",
"PostCode": "SE12 9QR",
"Country": "gb",
"UPRN": null
},
"LocationShortDescription": null,
"LocationLongDescription": ""
},
"ChargeDeviceManufacturer": null,
"ChargeDeviceModel": null,
"PublishStatusID": "1",
"DateCreated": "2014-08-19 05:15:02",
"DateUpdated": "2015-09-02 11:28:16",
"Attribution": "Source London",
"DateDeleted": "n/a",
"Connector": [
{
"ConnectorId": "1",
"ConnectorType": "3-pin Type G (BS1363)",
"RatedOutputkW": "3.7",
"RatedOutputVoltage": "230",
"RatedOutputCurrent": "16",
"ChargeMethod": "Single Phase AC",
"ChargeMode": "1",
"ChargePointStatus": "In service",
"TetheredCable": "0",
"Information": " x 3-pin square (BS 1363) - Standard (up to 3.7kW, 13-16A)",
"Validated": "0"
},
{
"ConnectorId": "1",
"ConnectorType": "3-pin Type G (BS1363)",
"RatedOutputkW": "3.7",
"RatedOutputVoltage": "230",
"RatedOutputCurrent": "16",
"ChargeMethod": "Single Phase AC",
"ChargeMode": "1",
"ChargePointStatus": "In service",
"TetheredCable": "0",
"Information": " x 3-pin square (BS 1363) - Standard (up to 3.7kW, 13-16A)",
"Validated": "0"
},
{
"ConnectorId": "2",
"ConnectorType": "Type 2 Mennekes (IEC62196)",
"RatedOutputkW": "7.0",
"RatedOutputVoltage": "230",
"RatedOutputCurrent": "32",
"ChargeMethod": "Single Phase AC",
"ChargeMode": "3",
"ChargePointStatus": "In service",
"TetheredCable": "0",
"Information": " x 7-pin 'Smart' eg Mennekes (IEC 62196) - Fast (7kW, 32A)",
"Validated": "0"
}
],
"DeviceOwner": {
"OrganisationName": "Source London",
"SchemeCode": "SRC_LDN",
"Website": "https://www.sourcelondon.net",
"TelephoneNo": "020 3056 8989"
},
"DeviceController": {
"OrganisationName": "Source London",
"SchemeCode": "SRC_LDN",
"Website": "https://www.sourcelondon.net",
"TelephoneNo": "020 3056 8989"
},
"DeviceAccess": [],
"DeviceNetworks": "Source London",
"ChargeDeviceStatus": "In service",
"PublishStatus": "Published",
"DeviceValidated": "0",
"RecordModerated": "Y",
"RecordLastUpdated": "2015-09-02 11:28:16",
"RecordLastUpdatedBy": "NCR Admin",
"PaymentRequiredFlag": false,
"PaymentDetails": "",
"SubscriptionRequiredFlag": true,
"SubscriptionDetails": "\u00a35 per annum for RFiD card",
"ParkingFeesFlag": false,
"ParkingFeesDetails": "",
"ParkingFeesUrl": null,
"AccessRestrictionFlag": false,
"AccessRestrictionDetails": "",
"PhysicalRestrictionFlag": false,
"PhysicalRestrictionText": "",
"OnStreetFlag": true,
"LocationType": "On-street",
"Bearing": null,
"Accessible24Hours": false
}
]
};
let myConnArr = [];
Array.from(myJson.ChargeDevice[0].Connector, conn =>
{
if(!myConnArr.includes(conn.ConnectorType)) myConnArr.push(conn.ConnectorType)
});
console.log(myConnArr.join(", \n"));
You could take a Set and check if the item is not in the set, then use the item and add this item to the set.
var array = [{ connector: ['ConnectorType1'] }, { connector: ['ConnectorType1', 'ConnectorType2', 'ConnectorType3'] }, { connector: ['ConnectorType1'] }, { connector: ['ConnectorType1', 'ConnectorType2'] }],
connectors = new Set;
array.forEach(({ connector }) => connector.forEach(c => {
if (connectors.has(c)) return;
console.log(c);
connectors.add(c);
}));
Not sure if this is what you're after, but here is a function that returns an array of the unique connectors within a ChargeDevice and a little test.
function getUniqueConnectors(data) {
var connectors = [];
for (let i in data.ChargeDevice) {
for (let x = 0; x < data.ChargeDevice[i].Connector.length; x++) {
if (connectors.indexOf(data.ChargeDevice[i].Connector[x].ConnectorType) === -1) {
connectors.push(data.ChargeDevice[i].Connector[x].ConnectorType);
}
}
}
return connectors;
}
var objectOne = {
"ChargeDevice": [
{
"ChargeDeviceId": "cfeedcdd5e287bef4b583158a12363f1",
"ChargeDeviceRef": "SRC_LDN60188",
"ChargeDeviceName": "2 Riddons Road",
"ChargeDeviceText": null,
"ChargeDeviceLocation": {
"Latitude": "51.431454",
"Longitude": "0.031175",
"Address": {
"SubBuildingName": null,
"BuildingName": "",
"BuildingNumber": "",
"Thoroughfare": "Riddons Road",
"Street": "Junction with Chinbrook Road",
"DoubleDependantLocality": null,
"DependantLocality": null,
"PostTown": "Leek",
"County": "Greater London",
"PostCode": "SE12 9QR",
"Country": "gb",
"UPRN": null
},
"LocationShortDescription": null,
"LocationLongDescription": ""
},
"ChargeDeviceManufacturer": null,
"ChargeDeviceModel": null,
"PublishStatusID": "1",
"DateCreated": "2014-08-19 05:15:02",
"DateUpdated": "2015-09-02 11:28:16",
"Attribution": "Source London",
"DateDeleted": "n/a",
"Connector": [
{
"ConnectorId": "1",
"ConnectorType": "3-pin Type G (BS1363)",
"RatedOutputkW": "3.7",
"RatedOutputVoltage": "230",
"RatedOutputCurrent": "16",
"ChargeMethod": "Single Phase AC",
"ChargeMode": "1",
"ChargePointStatus": "In service",
"TetheredCable": "0",
"Information": " x 3-pin square (BS 1363) - Standard (up to 3.7kW, 13-16A)",
"Validated": "0"
},
{
"ConnectorId": "2",
"ConnectorType": "Type 2 Mennekes (IEC62196)",
"RatedOutputkW": "7.0",
"RatedOutputVoltage": "230",
"RatedOutputCurrent": "32",
"ChargeMethod": "Single Phase AC",
"ChargeMode": "3",
"ChargePointStatus": "In service",
"TetheredCable": "0",
"Information": " x 7-pin 'Smart' eg Mennekes (IEC 62196) - Fast (7kW, 32A)",
"Validated": "0"
},
{
"ConnectorId": "2",
"ConnectorType": "Type 2 Mennekes (IEC62196)",
"RatedOutputkW": "7.0",
"RatedOutputVoltage": "230",
"RatedOutputCurrent": "32",
"ChargeMethod": "Single Phase AC",
"ChargeMode": "3",
"ChargePointStatus": "In service",
"TetheredCable": "0",
"Information": " x 7-pin 'Smart' eg Mennekes (IEC 62196) - Fast (7kW, 32A)",
"Validated": "0"
},
{
"ConnectorId": "2",
"ConnectorType": "Type 2 Mennekes (IEC62196)",
"RatedOutputkW": "7.0",
"RatedOutputVoltage": "230",
"RatedOutputCurrent": "32",
"ChargeMethod": "Single Phase AC",
"ChargeMode": "3",
"ChargePointStatus": "In service",
"TetheredCable": "0",
"Information": " x 7-pin 'Smart' eg Mennekes (IEC 62196) - Fast (7kW, 32A)",
"Validated": "0"
},
],
"DeviceOwner": {
"OrganisationName": "Source London",
"SchemeCode": "SRC_LDN",
"Website": "https://www.sourcelondon.net",
"TelephoneNo": "020 3056 8989"
},
"DeviceController": {
"OrganisationName": "Source London",
"SchemeCode": "SRC_LDN",
"Website": "https://www.sourcelondon.net",
"TelephoneNo": "020 3056 8989"
},
"DeviceAccess": [],
"DeviceNetworks": "Source London",
"ChargeDeviceStatus": "In service",
"PublishStatus": "Published",
"DeviceValidated": "0",
"RecordModerated": "Y",
"RecordLastUpdated": "2015-09-02 11:28:16",
"RecordLastUpdatedBy": "NCR Admin",
"PaymentRequiredFlag": false,
"PaymentDetails": "",
"SubscriptionRequiredFlag": true,
"SubscriptionDetails": "\u00a35 per annum for RFiD card",
"ParkingFeesFlag": false,
"ParkingFeesDetails": "",
"ParkingFeesUrl": null,
"AccessRestrictionFlag": false,
"AccessRestrictionDetails": "",
"PhysicalRestrictionFlag": false,
"PhysicalRestrictionText": "",
"OnStreetFlag": true,
"LocationType": "On-street",
"Bearing": null,
"Accessible24Hours": false
},
]
};
console.log(getUniqueConnectors(objectOne)); //["3-pin Type G (BS1363)", "Type 2 Mennekes (IEC62196)"]
Is it possible to modify the following so that on the foreach it would reverse so that latest date of data is first rather than oldest to newest?
var json = {
"TrackingRecord": {
"Authorised": "Authorised(5.77.48.131)",
"DeliveryAddress": {
"CompanyName": "JAMES DERICK",
"Address1": "6",
"Address2": "LIBER HOUSE",
"Address3": "OLYMPIAN",
"Town": "YORK",
"Postcode": "YO10 3UF",
"ContactName": "JAMES DERICK",
"ContactTelephone": "7507346318"
},
"CollectionAddress": {
"CompanyName": "AMBIENT LOUNGE LTD",
"Address1": "UNIT 3 LONG HEDGE LANE INDUSTR",
"Address2": "BOTTESFORD",
"Address3": {
},
"Town": "NOTTINGHAM",
"Postcode": "NG13 0BF",
"ContactName": "SARAH KIRBY",
"ContactTelephone": "07879 442266074"
},
"ConsignmentInformation": {
"Pieces": "1",
"Pallets": "0",
"Weight": "10",
"Service": "Priority 1",
"DeliveryDate": "2016-02-29T00:00:00",
"ItemsDelivered": "1",
"ConsignmentRef": "2838",
"SpecialInstructions": "JAMES DERICK 7507346318 {JAMES\u003Cbr\u003E14075#GMAIL.COM}\u003Cbr\u003E",
"AdditionalReferencesInformation": {
"AdditionalReferences": {
"Reference": "2838"
}
}
},
"MovementInformation": {
"Movement": [{
"MovementDate": "2016-02-25T00:00:00",
"MovementTime": "0001-01-01T10:00:04",
"Description": "Created By EZEEWEB",
"DeliveryDepot": "Leeds",
"Round": "019",
"DeliveryDate": "2016-02-26T00:00:00",
"PackagesReceived": "0",
"PackagesDelivered": "0"
}, {
"MovementDate": "2016-02-26T00:00:00",
"MovementTime": "0001-01-01T07:11:53",
"Description": "Out to deliver",
"DeliveryDepot": "Leeds",
"Round": "019",
"DeliveryDate": "2016-02-26T00:00:00",
"PackagesReceived": "1",
"PackagesDelivered": "0"
}, {
"MovementDate": "2016-02-26T00:00:00",
"MovementTime": "0001-01-01T11:00:53",
"Description": "Failed - Other reason",
"DeliveryDepot": "Leeds",
"Round": "019",
"DeliveryDate": "2016-02-29T00:00:00",
"PackagesReceived": "1",
"PackagesDelivered": "0"
}, {
"MovementDate": "2016-02-27T00:00:00",
"MovementTime": "0001-01-01T05:59:32",
"Description": "Out to deliver",
"DeliveryDepot": "Leeds",
"Round": "019",
"DeliveryDate": "2016-02-29T00:00:00",
"PackagesReceived": "1",
"PackagesDelivered": "0"
}, {
"MovementDate": "2016-02-29T00:00:00",
"MovementTime": "0001-01-01T10:55:43",
"Description": "Delivered",
"DeliveryDepot": "Leeds",
"Round": "019",
"DeliveryDate": "2016-02-29T00:00:00",
"PackagesReceived": "1",
"PackagesDelivered": "1"
}]
},
"TimedInformation": {
"TimedDelivery": {
"Signature": "DERICK",
"SignatureDate": "2016-02-29T00:00:00",
"SignatureTime": "0001-01-01T10:55:00"
}
},
"ScanInformation": {
"Scan": [{
"PieceID": "148426702251072001",
"Description": "Auto Inbound Scan ()",
"Depot": "Newark",
"ScanDate": "2016-02-25T00:00:00",
"ScanTime": "0001-01-01T17:12:01",
"ScannedBy": "NWK CONVYR"
}, {
"PieceID": "148426702251072001",
"Description": "Auto Inbound Scan ()",
"Depot": "Leeds",
"ScanDate": "2016-02-26T00:00:00",
"ScanTime": "0001-01-01T02:22:08",
"ScannedBy": "LDS CONVYR"
}, {
"PieceID": "148426702251072001",
"Description": "Load C & D (019)",
"Depot": "Leeds",
"ScanDate": "2016-02-26T00:00:00",
"ScanTime": "0001-01-01T03:37:45",
"ScannedBy": "CJONES"
}, {
"PieceID": "148426702251072001",
"Description": "Load C & D (019)",
"Depot": "Leeds",
"ScanDate": "2016-02-26T00:00:00",
"ScanTime": "0001-01-01T23:43:22",
"ScannedBy": "CJONES"
}]
},
"ImageInformation": {
"PODImage": {
"URL": "http:\/\/www.tpeweb.co.uk\/ezpod\/tpenas\/valid\/20160229\/014842672838___________00000_01.tif"
}
}
}
}
json.TrackingRecord.MovementInformation.Movement.forEach(function(item) {
//console.log(item);
item.MovementDate = moment(item.MovementDate).format('ddd, Do of MMM YYYY');
item.MovementTime = moment(item.MovementTime).format('hh:mm a');
$("#movement tbody").append("<tr><td>" + item.MovementDate + "</td><td>" + item.MovementTime + "</td><td>" + item.Description + "</td></tr>");
})
<script src="https://cdn.jsdelivr.net/momentjs/2.11.2/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="movement">
<thead>
<tr>
<th>Date</th>
<th>Time</th>
<th>Status</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Not with plain forEach. Possibilities:
Assume it is in ascending order. Loop indices from length - 1 to 0. Nondestructive.
Assume it is in ascending order. Apply reverse, then forEach. Destructive.
Assume it is unsorted. Sort the array, then apply forEach. Destructive.
Assume it is unsorted. Create an array of indices, sort the indices by the corresponding values in the array, apply forEach on indices and access array members. Nondestructive.
Assume it is unsorted. Clone the array using slice, then apply sort and forEach. Nondestructive.
A non–destructive way to iterate backwards over an array (other than a plain for loop) is reduceRight:
json.TrackingRecord.MovementInformation.Movement.reduceRight(function(acc, item) {
// do stuff
}, null);
You could change
json.TrackingRecord.MovementInformation.Movement.forEach(function(item) {
to
json.TrackingRecord.MovementInformation.Movement.reverse().forEach(function(item) {
^^^^^^^^^
var json = {
"TrackingRecord": {
"Authorised": "Authorised(5.77.48.131)",
"DeliveryAddress": {
"CompanyName": "JAMES DERICK",
"Address1": "6",
"Address2": "LIBER HOUSE",
"Address3": "OLYMPIAN",
"Town": "YORK",
"Postcode": "YO10 3UF",
"ContactName": "JAMES DERICK",
"ContactTelephone": "7507346318"
},
"CollectionAddress": {
"CompanyName": "AMBIENT LOUNGE LTD",
"Address1": "UNIT 3 LONG HEDGE LANE INDUSTR",
"Address2": "BOTTESFORD",
"Address3": {
},
"Town": "NOTTINGHAM",
"Postcode": "NG13 0BF",
"ContactName": "SARAH KIRBY",
"ContactTelephone": "07879 442266074"
},
"ConsignmentInformation": {
"Pieces": "1",
"Pallets": "0",
"Weight": "10",
"Service": "Priority 1",
"DeliveryDate": "2016-02-29T00:00:00",
"ItemsDelivered": "1",
"ConsignmentRef": "2838",
"SpecialInstructions": "JAMES DERICK 7507346318 {JAMES\u003Cbr\u003E14075#GMAIL.COM}\u003Cbr\u003E",
"AdditionalReferencesInformation": {
"AdditionalReferences": {
"Reference": "2838"
}
}
},
"MovementInformation": {
"Movement": [{
"MovementDate": "2016-02-25T00:00:00",
"MovementTime": "0001-01-01T10:00:04",
"Description": "Created By EZEEWEB",
"DeliveryDepot": "Leeds",
"Round": "019",
"DeliveryDate": "2016-02-26T00:00:00",
"PackagesReceived": "0",
"PackagesDelivered": "0"
}, {
"MovementDate": "2016-02-26T00:00:00",
"MovementTime": "0001-01-01T07:11:53",
"Description": "Out to deliver",
"DeliveryDepot": "Leeds",
"Round": "019",
"DeliveryDate": "2016-02-26T00:00:00",
"PackagesReceived": "1",
"PackagesDelivered": "0"
}, {
"MovementDate": "2016-02-26T00:00:00",
"MovementTime": "0001-01-01T11:00:53",
"Description": "Failed - Other reason",
"DeliveryDepot": "Leeds",
"Round": "019",
"DeliveryDate": "2016-02-29T00:00:00",
"PackagesReceived": "1",
"PackagesDelivered": "0"
}, {
"MovementDate": "2016-02-27T00:00:00",
"MovementTime": "0001-01-01T05:59:32",
"Description": "Out to deliver",
"DeliveryDepot": "Leeds",
"Round": "019",
"DeliveryDate": "2016-02-29T00:00:00",
"PackagesReceived": "1",
"PackagesDelivered": "0"
}, {
"MovementDate": "2016-02-29T00:00:00",
"MovementTime": "0001-01-01T10:55:43",
"Description": "Delivered",
"DeliveryDepot": "Leeds",
"Round": "019",
"DeliveryDate": "2016-02-29T00:00:00",
"PackagesReceived": "1",
"PackagesDelivered": "1"
}]
},
"TimedInformation": {
"TimedDelivery": {
"Signature": "DERICK",
"SignatureDate": "2016-02-29T00:00:00",
"SignatureTime": "0001-01-01T10:55:00"
}
},
"ScanInformation": {
"Scan": [{
"PieceID": "148426702251072001",
"Description": "Auto Inbound Scan ()",
"Depot": "Newark",
"ScanDate": "2016-02-25T00:00:00",
"ScanTime": "0001-01-01T17:12:01",
"ScannedBy": "NWK CONVYR"
}, {
"PieceID": "148426702251072001",
"Description": "Auto Inbound Scan ()",
"Depot": "Leeds",
"ScanDate": "2016-02-26T00:00:00",
"ScanTime": "0001-01-01T02:22:08",
"ScannedBy": "LDS CONVYR"
}, {
"PieceID": "148426702251072001",
"Description": "Load C & D (019)",
"Depot": "Leeds",
"ScanDate": "2016-02-26T00:00:00",
"ScanTime": "0001-01-01T03:37:45",
"ScannedBy": "CJONES"
}, {
"PieceID": "148426702251072001",
"Description": "Load C & D (019)",
"Depot": "Leeds",
"ScanDate": "2016-02-26T00:00:00",
"ScanTime": "0001-01-01T23:43:22",
"ScannedBy": "CJONES"
}]
},
"ImageInformation": {
"PODImage": {
"URL": "http:\/\/www.tpeweb.co.uk\/ezpod\/tpenas\/valid\/20160229\/014842672838___________00000_01.tif"
}
}
}
}
json.TrackingRecord.MovementInformation.Movement.reverse().forEach(function(item) {
//console.log(item);
item.MovementDate = moment(item.MovementDate).format('ddd, Do of MMM YYYY');
item.MovementTime = moment(item.MovementTime).format('hh:mm a');
$("#movement tbody").append("<tr><td>" + item.MovementDate + "</td><td>" + item.MovementTime + "</td><td>" + item.Description + "</td></tr>");
})
<script src="https://cdn.jsdelivr.net/momentjs/2.11.2/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="movement">
<thead>
<tr>
<th>Date</th>
<th>Time</th>
<th>Status</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Keep in mind that reverse actually modifies the array, it doesn't just return an array with the elements reversed. However, this is probably what you want considering it's supposed to be printed in that order.
I was wondering if it is possible to get the places of interest in a location based on the lattitude/longitude information or approximate street address gathered from a GPS system?
places of interest are defined in this context as: Restaurants, Resorts, Parks, malls, movie theaters, etc.
Are there some online services either with bing maps / google maps / something else, that provides such information in some parsed format?
Thank you
On the client side, you use the Google AJAX Search API to search for places of interest around a specific coordinate:
<!DOCTYPE html>
<html>
<head>
<title>Google AJAX Search API Demo</title>
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load('search', '1');
var localSearch;
function localSearchComplete() {
// Check that we got results
if (localSearch.results && localSearch.results.length > 0) {
// Loop through our results, printing them to the page.
var results = localSearch.results;
document.getElementById('content').innerHTML = "";
for (var i = 0; i < results.length; i++) {
document.getElementById('content').innerHTML +=
'<div style="clear: both;">' +
'<div style="float: left; width: 160px;">' + results[i].title + '</div>' +
'<div style="float: left; width: 80px;">' + results[i].lat + '</div>' +
'<div style="float: left; width: 80px;">' + results[i].lng + '</div>' +
'<div style="float: left; width: 140px;">' + results[i].streetAddress + '</div>' +
'<div style="float: left; width: 120px;">' + results[i].city + '</div>' +
'</div>';
}
}
}
function OnLoad() {
localSearch = new google.search.LocalSearch();
// Coordinates for "New York, NY"
localSearch.setCenterPoint("40.70, -74.00");
localSearch.setSearchCompleteCallback(this, localSearchComplete, null);
localSearch.execute("restaurants");
}
google.setOnLoadCallback(OnLoad);
</script>
</head>
<body style="font-family: Arial; font-size: 11px;">
<div id="content">Loading...</div>
</body>
</html>
The result would be the following:
Local Search Results http://img693.imageshack.us/img693/240/localsearch.png
To get the same results from the server side in JSON format, you may want to check the following article:
Google AJAX Search API: Flash and other Non-Javascript Environment
Basically you would be able to issue a request to Google in the following format:
http://ajax.googleapis.com/ajax/services/search/local?v=2.0&q=restaurants+40.70,-74.00
Which would return the following JSON:
{
"responseData": {
"results": [
{
"GsearchResultClass": "GlocalSearch",
"viewportmode": "explicit",
"listingType": "local",
"lat": "40.703684",
"lng": "-73.994861",
"accuracy": "8",
"title": "The River Cafe",
"titleNoFormatting": "The River Cafe",
"ddUrl": "http://www.google.com/maps?source\u003duds\u0026daddr\u003d1+Water+Street%2C+Brooklyn%2C+NY+%28The+River+Cafe%29+%4040.703684%2C-73.994861\u0026saddr\u003d40.70%2C-74.00",
"ddUrlToHere": "http://www.google.com/maps?source\u003duds\u0026daddr\u003d1+Water+Street%2C+Brooklyn%2C+NY+%28The+River+Cafe%29+%4040.703684%2C-73.994861\u0026iwstate1\u003ddir%3Ato",
"ddUrlFromHere": "http://www.google.com/maps?source\u003duds\u0026saddr\u003d1+Water+Street%2C+Brooklyn%2C+NY+%28The+River+Cafe%29+%4040.703684%2C-73.994861\u0026iwstate1\u003ddir%3Afrom",
"streetAddress": "1 Water Street",
"city": "Brooklyn",
"region": "NY",
"country": "United States",
"staticMapUrl": "http://mt.google.com/mapdata?cc\u003dus\u0026tstyp\u003d5\u0026Point\u003db\u0026Point.latitude_e6\u003d40703684\u0026Point.longitude_e6\u003d-73994861\u0026Point.iconid\u003d15\u0026Point\u003de\u0026w\u003d150\u0026h\u003d100\u0026zl\u003d4",
"url": "http://www.google.com/maps/place?source\u003duds\u0026q\u003drestaurants\u0026cid\u003d9181090609208620883",
"content": "",
"maxAge": 604800,
"phoneNumbers": [
{
"type": "",
"number": "(718) 522-5200"
}
],
"addressLines": [
"1 Water Street",
"Brooklyn, NY"
]
},
{
"GsearchResultClass": "GlocalSearch",
"viewportmode": "explicit",
"listingType": "local",
"lat": "40.702956",
"lng": "-73.994105",
"accuracy": "8",
"title": "Pete\u0026#39;s Downtown \u003cb\u003eRestaurant\u003c/b\u003e",
"titleNoFormatting": "Pete's Downtown Restaurant",
"ddUrl": "http://www.google.com/maps?source\u003duds\u0026daddr\u003d1+Cadman+Plaza+West%2C+Brooklyn%2C+NY+%28Pete%27s+Downtown+Restaurant%29+%4040.702956%2C-73.994105\u0026saddr\u003d40.70%2C-74.00",
"ddUrlToHere": "http://www.google.com/maps?source\u003duds\u0026daddr\u003d1+Cadman+Plaza+West%2C+Brooklyn%2C+NY+%28Pete%27s+Downtown+Restaurant%29+%4040.702956%2C-73.994105\u0026iwstate1\u003ddir%3Ato",
"ddUrlFromHere": "http://www.google.com/maps?source\u003duds\u0026saddr\u003d1+Cadman+Plaza+West%2C+Brooklyn%2C+NY+%28Pete%27s+Downtown+Restaurant%29+%4040.702956%2C-73.994105\u0026iwstate1\u003ddir%3Afrom",
"streetAddress": "1 Cadman Plaza West",
"city": "Brooklyn",
"region": "NY",
"country": "United States",
"staticMapUrl": "http://mt.google.com/mapdata?cc\u003dus\u0026tstyp\u003d5\u0026Point\u003db\u0026Point.latitude_e6\u003d40702956\u0026Point.longitude_e6\u003d-73994105\u0026Point.iconid\u003d15\u0026Point\u003de\u0026w\u003d150\u0026h\u003d100\u0026zl\u003d4",
"url": "http://www.google.com/maps/place?source\u003duds\u0026q\u003drestaurants\u0026cid\u003d4933341782274549162",
"content": "",
"maxAge": 604800,
"phoneNumbers": [
{
"type": "",
"number": "(718) 858-3510"
}
],
"addressLines": [
"1 Cadman Plaza West",
"Brooklyn, NY"
]
},
{
"GsearchResultClass": "GlocalSearch",
"viewportmode": "explicit",
"listingType": "local",
"lat": "40.702726",
"lng": "-73.993499",
"accuracy": "8",
"title": "Grimaldi\u0026#39;s Pizzeria",
"titleNoFormatting": "Grimaldi's Pizzeria",
"ddUrl": "http://www.google.com/maps?source\u003duds\u0026daddr\u003d19+Old+Fulton+St%2C+%2C+NY+%28Grimaldi%27s+Pizzeria%29+%4040.702726%2C-73.993499\u0026saddr\u003d40.70%2C-74.00",
"ddUrlToHere": "http://www.google.com/maps?source\u003duds\u0026daddr\u003d19+Old+Fulton+St%2C+%2C+NY+%28Grimaldi%27s+Pizzeria%29+%4040.702726%2C-73.993499\u0026iwstate1\u003ddir%3Ato",
"ddUrlFromHere": "http://www.google.com/maps?source\u003duds\u0026saddr\u003d19+Old+Fulton+St%2C+%2C+NY+%28Grimaldi%27s+Pizzeria%29+%4040.702726%2C-73.993499\u0026iwstate1\u003ddir%3Afrom",
"streetAddress": "19 Old Fulton St",
"city": "",
"region": "NY",
"country": "United States",
"staticMapUrl": "http://mt.google.com/mapdata?cc\u003dus\u0026tstyp\u003d5\u0026Point\u003db\u0026Point.latitude_e6\u003d40702726\u0026Point.longitude_e6\u003d-73993499\u0026Point.iconid\u003d15\u0026Point\u003de\u0026w\u003d150\u0026h\u003d100\u0026zl\u003d4",
"url": "http://www.google.com/maps/place?source\u003duds\u0026q\u003drestaurants\u0026cid\u003d4244157563901397553",
"content": "",
"maxAge": 604800,
"phoneNumbers": [
{
"type": "",
"number": "(718) 858-4300"
}
],
"addressLines": [
"19 Old Fulton St",
"Brooklyn, NY"
]
},
{
"GsearchResultClass": "GlocalSearch",
"viewportmode": "explicit",
"listingType": "local",
"lat": "40.695108",
"lng": "-73.996252",
"accuracy": "8",
"title": "Teresa\u0026#39;s \u003cb\u003eRestaurant\u003c/b\u003e",
"titleNoFormatting": "Teresa's Restaurant",
"ddUrl": "http://www.google.com/maps?source\u003duds\u0026daddr\u003d80+Montague+Street%2C+Brooklyn%2C+NY+%28Teresa%27s+Restaurant%29+%4040.695108%2C-73.996252\u0026saddr\u003d40.70%2C-74.00",
"ddUrlToHere": "http://www.google.com/maps?source\u003duds\u0026daddr\u003d80+Montague+Street%2C+Brooklyn%2C+NY+%28Teresa%27s+Restaurant%29+%4040.695108%2C-73.996252\u0026iwstate1\u003ddir%3Ato",
"ddUrlFromHere": "http://www.google.com/maps?source\u003duds\u0026saddr\u003d80+Montague+Street%2C+Brooklyn%2C+NY+%28Teresa%27s+Restaurant%29+%4040.695108%2C-73.996252\u0026iwstate1\u003ddir%3Afrom",
"streetAddress": "80 Montague Street",
"city": "Brooklyn",
"region": "NY",
"country": "United States",
"staticMapUrl": "http://mt.google.com/mapdata?cc\u003dus\u0026tstyp\u003d5\u0026Point\u003db\u0026Point.latitude_e6\u003d40695108\u0026Point.longitude_e6\u003d-73996252\u0026Point.iconid\u003d15\u0026Point\u003de\u0026w\u003d150\u0026h\u003d100\u0026zl\u003d4",
"url": "http://www.google.com/maps/place?source\u003duds\u0026q\u003drestaurants\u0026cid\u003d12686375620276309855",
"content": "",
"maxAge": 604800,
"phoneNumbers": [
{
"type": "",
"number": "(718) 797-3996"
}
],
"addressLines": [
"80 Montague Street",
"Brooklyn, NY"
]
}
],
"cursor": {
"pages": [
{
"start": "0",
"label": 1
},
{
"start": "4",
"label": 2
},
{
"start": "8",
"label": 3
},
{
"start": "12",
"label": 4
}
],
"estimatedResultCount": "189307",
"currentPageIndex": 0,
"moreResultsUrl": "http://www.google.com/local?oe\u003dutf8\u0026ie\u003dutf8\u0026num\u003d4\u0026mrt\u003dyp%2Cloc\u0026sll\u003d37.779160%2C-122.420090\u0026start\u003d0\u0026hl\u003den\u0026q\u003drestaurants+40.70%2C-74.00"
},
"viewport": {
"center": {
"lat": "40.699396",
"lng": "-73.99675"
},
"span": {
"lat": "0.010291",
"lng": "0.007801"
},
"sw": {
"lat": "40.69425",
"lng": "-74.00065"
},
"ne": {
"lat": "40.70454",
"lng": "-73.99285"
}
}
},
"responseDetails": null,
"responseStatus": 200
}
The Google AJAX Search API documentation provides some code snippets that demonstrate API access in Java, PHP, Python, Perl and Flash.