Related
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 have mapped and filtered two objects. I've hit a wall in my thinking. I cannot see how to add the key/value from one object to the other when the values match.
This type of sort is fairly new to me and wearing my logic thinking out, so any help will be appreciated.
I want to add the 'lat' and 'lon' values, with keys from the 'todaysDataPostcode' object, to the 'data' object.
This should be done when the postcodes match.
I'm using an approach I have done before, but the final stage is different and it's proving difficult to figure out
here's the code:
addLatLon = (location, latLon) => {
return location.map(compiledDataObj => {
const objectsWithSameLocation = latLon.filter(dataObj => {
return dataObj.postcode === compiledDataObj.postcode;
});
objectsWithSameLocation.map(obj => {
//here we want to match the postcode of the object we're running through
// so its like
compiledDataObj.postcode[obj.postcode]
// return console.log('location.postcode', location.map(i => i.postcode), 'obj.postcode', obj.postcode)
});
});
};
Here are the 2 datasets. The first one is only a partial version as this will be sufficient to implement logic.
Below is: 'data'
[
{
"location": "City of London",
"postcode": "EC1A 7BE",
"year": {
"10": "464436",
"11": "442413",
"12": "525723",
"13": "465451",
"14": "625001",
"15": "783667",
"16": "736788",
"17": "820305",
"18": "802129",
"19": "864034",
"95": "91449",
"96": "108999",
"97": "116343",
"98": "124382",
"99": "149143",
"00": "173738",
"01": "284262",
"02": "344239",
"03": "261645",
"04": "326913",
"05": "330363",
"06": "316121",
"07": "360923",
"08": "471861",
"09": "400317"
}
},
{
"location": "Barking & Dagenham",
"postcode": "RM9 4TP",
"year": {
"10": "162905",
"11": "163821",
"12": "163899",
"13": "167919",
"14": "184884",
"15": "220070",
"16": "258758",
"17": "282441",
"18": "291548",
"19": "298333",
"95": "50460",
"96": "50828",
"97": "54459",
"98": "57559",
"99": "64532",
"00": "71079",
"01": "82343",
"02": "98713",
"03": "134750",
"04": "150115",
"05": "164484",
"06": "162340",
"07": "176577",
"08": "194235",
"09": "166798"
}
}]
Here is the second data set: 'todaysDataPostcode'
[{
"postcode": "EC1A 7BE",
"longitude": -0.100404,
"latitude": 51.51775
},
{
"postcode": "RM9 4TP",
"longitude": 0.127884,
"latitude": 51.539774
},
{
"postcode": "EN5 5RP",
"longitude": -0.194074,
"latitude": 51.65044
},
{
"postcode": "DA16 3DN",
"longitude": 0.102535,
"latitude": 51.464737
},
{
"postcode": "HA9 9AA",
"longitude": -0.279243,
"latitude": 51.563322
},
{
"postcode": "BR1 3NN",
"longitude": 0.017131,
"latitude": 51.40827
},
{
"postcode": "NW1 8QL",
"longitude": -0.142696,
"latitude": 51.53929
},
{
"postcode": "CR2 7PA",
"longitude": -0.094105,
"latitude": 51.36292
}]
i want to add the
As mentioned above this is the expected result, I can't hit the result and i am lost right now.
"I want to add the 'lat' and 'lon' values, with keys from the 'todaysDataPostcode' object, to the 'data' object.
This should be done when the postcodes match."
Is that what you've been after?
const arr1 = [{"location":"City of London","postcode":"EC1A 7BE","year":{"10":"464436","11":"442413","12":"525723","13":"465451","14":"625001","15":"783667","16":"736788","17":"820305","18":"802129","19":"864034","95":"91449","96":"108999","97":"116343","98":"124382","99":"149143","00":"173738","01":"284262","02":"344239","03":"261645","04":"326913","05":"330363","06":"316121","07":"360923","08":"471861","09":"400317"}},{"location":"Barking & Dagenham","postcode":"RM9 4TP","year":{"10":"162905","11":"163821","12":"163899","13":"167919","14":"184884","15":"220070","16":"258758","17":"282441","18":"291548","19":"298333","95":"50460","96":"50828","97":"54459","98":"57559","99":"64532","00":"71079","01":"82343","02":"98713","03":"134750","04":"150115","05":"164484","06":"162340","07":"176577","08":"194235","09":"166798"}}];
const arr2 = [{"postcode":"EC1A 7BE","longitude":-0.100404,"latitude":51.51775},{"postcode":"RM9 4TP","longitude":0.127884,"latitude":51.539774},{"postcode":"EN5 5RP","longitude":-0.194074,"latitude":51.65044},{"postcode":"DA16 3DN","longitude":0.102535,"latitude":51.464737},{"postcode":"HA9 9AA","longitude":-0.279243,"latitude":51.563322},{"postcode":"BR1 3NN","longitude":0.017131,"latitude":51.40827},{"postcode":"NW1 8QL","longitude":-0.142696,"latitude":51.53929},{"postcode":"CR2 7PA","longitude":-0.094105,"latitude":51.36292}];
const merged = arr1.map(e => (coords = arr2.find(ee => ee.postcode == e.postcode), Object.assign(e,{longitude:coords['longitude'],latitude:coords['latitude']})));
console.log(merged);
.as-console-wrapper{ min-height: 100% }
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)"]
I am returning json string from web service and I can easily access it but sometime it behave strange and I can not find why.
Here is json string that I am getting through web service
{"current":"2014-10-07T17:53:03+02:00","T1":{"0":[null],"1":[null],"2":[null],"3":[null],"4":[null],"5":[null],"6":[{"name":"ABC","value":63}]},"T2":{"0":[null],"1":[null],"2":[null],"3":[null],"4":[null],"5":[null]},"T3":{"0":[null],"1":[null],"2":[null],"3":[null],"4":[null],"5":[null]},"T4":{"0":[null],"1":[null],"2":[null],"3":[null],"4":[null],"5":[null]},"T5":{"0":[null],"1":[null],"2":[null],"3":[null],"4":[null],"5":[null]}}
I can access them easily and it is working fine except when there is null on 0th position of any T1,T2,T3...etc. It return this error TypeError: Cannot read property '0' of undefined
This is how I am accessing data
if(json.T1 != undefined) {
for (var i = 0; i < len; i++) {
if(json.T1[i][0] == null) {
t1.push(NaN)
}
else
{
t1.push(json.T1[i][0]["value"])
}
}
}
I dont understand why this works in all the cases excpet having null of 0th position of T1, T2...etc
You have to change some things.
Try this way: http://jsfiddle.net/csdtesting/jww96u92/
var k = {
"current": "2014-10-07T17:53:03+02:00",
"T1": {
"0": [null],
"1": [null],
"2": [null],
"3": [null],
"4": [null],
"5": [null],
"6": [{
"name": "ABC",
"value": 63
}]
},
"T2": {
"0": [null],
"1": [null],
"2": [null],
"3": [null],
"4": [null],
"5": [null]
},
"T3": {
"0": [null],
"1": [null],
"2": [null],
"3": [null],
"4": [null],
"5": [null]
},
"T4": {
"0": [null],
"1": [null],
"2": [null],
"3": [null],
"4": [null],
"5": [null]
},
"T5": {
"0": [null],
"1": [null],
"2": [null],
"3": [null],
"4": [null],
"5": [null]
}
};
var t1 = [];
console.log(k);
if (k.T1 != undefined) {
$.each(k.T1, function(i, item) {
if (item[0] == null) {
t1.push(NaN)
} else {
alert("I just put " + item[0]["value"] + "in t1 array!Thanks!");
t1.push(item[0]["value"])
}
console.log(item);
});
console.log(t1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
That's because the len property doesn't represent the right length of the items that are into the T1 object.
Try to get the length by enumerating the T1 object properties.
var len = 0;
for(var item in json.T1){
len++;
}
And then, try the script you provided. This should work.
I have an object like below. Trying to rearrange it in ascending order based on value. Similar to Javascript array sort method.
var masterList = {
"1": "google",
"2": "yahoo",
"3": "msn",
"4": "stackoverflow",
"5": "github",
"6": "jsfiddle",
"7": "amazon",
"8": "ebay"
}
Please let me know the better solution...
JavaScript objects have no order. Even though most browsers do iterate in the same order the properties were created, there's no guarantee, so sorting is not supported on objects.
See here for more info: Does JavaScript Guarantee Object Property Order?
You might also be interested in what John Resig has got to say on the matter.
If you need a sort-able list, you'll have to store it as an array of objects:
var masterList = [
{ key: 1, val: "google" },
{ key: 2, val: "yahoo" },
{ key: 3, val: "msn" },
{ key: 4, val: "stackoverflow" },
{ key: 5, val: "github" },
{ key: 6, val: "jsfiddle" },
{ key: 7, val: "amazon" },
{ key: 8, val: "ebay" }
];
Then, to sort them, just use the regular array's sort method:
masterList = masterList.sort(function (a, b) {
return a.val.localeCompare( b.val );
});
Here's the fiddle: http://jsfiddle.net/ASrUD/
var obj = {
"1": "google",
"2": "yahoo",
"3": "msn",
"4": "stackoverflow",
"5": "github",
"6": "jsfiddle",
"7": "amazon",
"8": "ebay"
};
var arr = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
arr.push(obj[key]);
}
}
alert(arr.sort());
This will sort your values in ascending order. let me give sometime will revert you with how to convert that to an object.
var masterList = {
"2": "yahoo",
"3": "msn",
"4": "stackoverflow",
"5": "github",
"6": "jsfiddle",
"7": "amazon",
"8": "ebay",
"1": "google",
}
var masterList_ = {}
Object.keys(masterList).sort().forEach(a=>masterList_[a]=masterList[a])
console.log(masterList_)