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)"]
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 a json object with array of data.i want to filter it with another array.
MY .ts file is as follows.
let filter_bank_id=[4,25,6,1];
console.log(filter_bank_id.length);
if(data.offers){
let last =data.offers.filter(offer=>{
for(let i=0;i<filter_bank_id.length;i++){
if(data.offers[i]){
let bank=filter_bank_id[i];
if(bank){
if(bank===data.offers[i].bank_id){
return offer;
}
}
}else{
alert("nodata");
}
}
});
console.log(last);
}
Here offers is the json object with multiple data.i want to filter it with filter_bank_id array.That means i want only offers with bank_id 4,25,6,1 as in the filter_bank_id array.But it is not working.
problem is with " let last =data.offers.filter(offer=>" this line.when i give debugger it is not entering into it.My offers json object is below.
offers= [
{
"image": "assets\/banks\/axi1419231043.jpg",
"offerid": 1,
"id": "1",
"bank_id": "1",
"name": "AXIS BANK",
"bank_interest": "10.99",
"emi": "2,174",
"processing_fee": "990",
"precloser_cost": "0 %",
"part_pay": "Yes",
"insurance": null,
"conditions": "",
"intrest_1_year": 0,
"intrest_total": 0
},
{
"image": "assets\/banks\/hdfc1418896652.png",
"offerid": 7,
"id": "4",
"bank_id": "4",
"name": "HDFC BANK",
"bank_interest": "10.99",
"emi": "2,174",
"processing_fee": "500",
"precloser_cost": "4.49 % for 12-24 months,3.37 % for 24-36 months,2.25 % for 36-60 months,",
"part_pay": "Yes",
"insurance": "1,362",
"conditions": "",
"intrest_1_year": 0,
"intrest_total": 0
},
{
"image": "assets\/banks\/scb1438520764.png",
"offerid": 2,
"id": "16",
"bank_id": "16",
"name": "SCB",
"bank_interest": "11.00",
"emi": "2,175",
"processing_fee": "1000",
"precloser_cost": "0 %",
"part_pay": "Yes",
"insurance": null,
"conditions": "",
"intrest_1_year": 0,
"intrest_total": 0
},
{
"image": "assets\/banks\/citi1419219218.png",
"offerid": 3,
"id": "2",
"bank_id": "2",
"name": "CITI BANK",
"bank_interest": "11.49",
"emi": "2,199",
"processing_fee": "2999",
"precloser_cost": "2 %",
"part_pay": "Yes",
"insurance": null,
"conditions": "",
"intrest_1_year": 0,
"intrest_total": 0
},
];
What is the problem with my filter.please help me.Thank in advance.
Use filter like this
offers.filter((offer) => filter_bank_ids.indexOf(offer.bank_id) > -1)
Also check your types before using this snippet. I hope this will help you
I am new to Aurelia.
I'm trying to iterate (repeat.for) through some json that looks like below. I am able to do so with a manual concat but the number of artists is variable. Below for example works.
return this.http.fetch(baseUrl + "/artists/" + token + "&search=" + searchCreator)
.then(response => response.json())
.then(response => {
//for (var i = 0; i < response.resultsCount; i++){
// response += response.artists[i].objects;
//}
return response.artists[0].objects.concat(response.artists[1].objects);
});
How can I return all objects for all artists? I've tried doing this with a for loop but I can't get it to work. Should I return response.artists and then work with that in my view model? This is what the view looks like:
<tr repeat.for="item of items">
<td>${item.title}</td>
<td>${item.displayName}</td>
<td>${item.objectNumber}</td>
</tr>
json example:
{
"source": "My Museum",
"language": "EN",
"resultsCount": 58,
"artists":
[{
"artistID": 47171,
"alphaSort": "Smith Eloise Vega",
"displayName": "Eloise Vega Smith",
"beginDate": "0",
"endDate": "0",
"displayDate": "",
"sex": "Female",
"nationality": "",
"objectCount": 1,
"objects":
[{
"objectNumber": "209.2015",
"objectID": 188963,
"title": "Album cover for Urszula Dudziak, Newborn Light",
"displayName": "Eloise Vega Smith",
"alphaSort": "Smith Eloise Vega",
"artistID": 47171,
"displayDate": "",
"dated": "1974",
"dateBegin": 1974,
"dateEnd": 1974,
"medium": "Lithograph",
"dimensions": "12 1/2 x 12 1/4\" (31.8 x 31.1 cm)",
"department": "Architecture & Design",
"classification": "A&D Graphic Design",
"onView": 0,
"provenance": "",
"description": "",
"objectStatusID": 1,
"creditLine": "Committee on Architecture and Design Funds",
"imageID": "502407",
"thumbnail": "http:///TMSImages/Size1/Images/TR15211_10_RICR.jpg",
"fullImage": "http:///TMSImages/Size3/Images/TR15211_10_RICR.jpg",
"lastModifiedDate": "2015-09-17T01:00:08"
}
]
},
{
"artistID": 5479,
"alphaSort": "Smith Charles",
"displayName": "Charles Smith",
"beginDate": "1893",
"endDate": "1987",
"displayDate": "American, 1893–1987",
"sex": "Male",
"nationality": "American",
"objectCount": 6,
"objects":
[{
"objectNumber": "369.1941",
"objectID": 67911,
"title": "Red Circle",
"displayName": "Charles Smith",
"alphaSort": "Smith Charles",
"artistID": 5479,
"displayDate": "American, 1893–1987",
"dated": "1940",
"dateBegin": 1940,
"dateEnd": 1940,
"medium": "Monoprint",
"dimensions": "Sheet 21 1/8 x 14 3/4\" (53.8 x 37.5 cm) Comp. 20 x 14 3/4\" (50.8 x 37.5 cm)",
"department": "Prints & Illustrated Books",
"classification": "Print",
"onView": 0,
"provenance": "",
"description": "Color monoprint, printed from movable forms",
"objectStatusID": 1,
"creditLine": "Purchase",
"imageID": "260293",
"thumbnail": "http:///TMSImages/Size1/Images/369_1941_RICR.jpg",
"fullImage": "http:///TMSImages/Size3/Images/369_1941_RICR.jpg",
"lastModifiedDate": "2015-03-31T01:06:18"
},
{
"objectNumber": "214.1942",
"objectID": 64517,
"title": "Abstraction",
"displayName": "Charles Smith",
"alphaSort": "Smith Charles",
"artistID": 5479,
"displayDate": "American, 1893–1987",
"dated": "c. 1942",
"dateBegin": 1942,
"dateEnd": 1942,
"medium": "Woodcut",
"dimensions": "composition (irreg.): 11 1/4 x 3 3/4\" (28.5 x 9.6 cm); sheet: 14 9/16 x 7 1/16\" (37 x 17.9 cm)",
"department": "Prints & Illustrated Books",
"classification": "Print",
"onView": 0,
"provenance": "",
"description": "Woodcut, printed in black, dark green yellow, deep blue and strong red brown",
"objectStatusID": 1,
"creditLine": "Given anonymously",
"imageID": "195213",
"thumbnail": "http:///TMSImages/Size1/Images/214_1942_RICR.jpg",
"fullImage": "http:///TMSImages/Size3/Images/214_1942_RICR.jpg",
"lastModifiedDate": "2014-09-19T01:05:22"
},
etc.....
I appreciate the help!
If you are familiar with LINQ, you could use a library like jslinq and do the following:
return jslinq(response.artists)
.selectMany(function(artist){
return artist.objects
}).toList();
of course I would only include jslinq if I planned to use it more than once in the project. If you don't want the overhead, your solution with concat should work just fine:
var result = [];
for(var i = 0; i < response.artists.length; i++) {
result = result.concat(response.artists[i].objects);
}
return result;
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'm trying to loop through all this array data but it won't work out how to display it all via jquery using the .each function? Can someone help me out?
ARRAY:
{
"ListOrdersResult": {
"Orders": {
"Order": [
{
"ShipmentServiceLevelCategory": "Standard",
"OrderTotal": {
"Amount": "29.00",
"CurrencyCode": "GBP"
},
"ShipServiceLevel": "Std UK Dom",
"LatestShipDate": "2013-11-28T23:59:59Z",
"MarketplaceId": "A1F83G8C2ARO7P",
"SalesChannel": "Amazon.co.uk",
"ShippingAddress": {
"Phone": "0800 000 0000",
"PostalCode": "A11 H11",
"Name": "stephanie ross",
"CountryCode": "GB",
"StateOrRegion": "regiion",
"AddressLine2": "cairnbulg",
"AddressLine1": "loco 2222 name",
"City": "fraserburgh"
},
"ShippedByAmazonTFM": "false",
"OrderType": "StandardOrder",
"FulfillmentChannel": "MFN",
"BuyerEmail": "c9tkdmn724jpgkd#blahblah.com",
"OrderStatus": "Shipped",
"BuyerName": "custom A Ross",
"LastUpdateDate": "2013-11-27T14:26:53Z",
"EarliestShipDate": "2013-11-27T00:00:00Z",
"PurchaseDate": "2013-11-26T22:25:39Z",
"NumberOfItemsUnshipped": "0",
"AmazonOrderId": "205-8108202-4976362",
"NumberOfItemsShipped": "1",
"PaymentMethod": "Other"
},
{
"ShipmentServiceLevelCategory": "Standard",
"OrderTotal": {
"Amount": "29.00",
"CurrencyCode": "GBP"
},
"ShipServiceLevel": "Std UK Dom",
"LatestShipDate": "2013-11-28T23:59:59Z",
"MarketplaceId": "A1F83G8C2ARO7P",
"SalesChannel": "Amazon.co.uk",
"ShippingAddress": {
"Phone": "0800 000 0000",
"PostalCode": "A11 H11",
"Name": "stephanie ross",
"CountryCode": "GB",
"StateOrRegion": "regiion",
"AddressLine2": "cairnbulg",
"AddressLine1": "loco 2222 name",
"City": "fraserburgh"
},
"ShippedByAmazonTFM": "false",
"OrderType": "StandardOrder",
"FulfillmentChannel": "MFN",
"BuyerEmail": "c9tkdmn724jpgkd#blahblah.com",
"OrderStatus": "Shipped",
"BuyerName": "custom A Ross",
"LastUpdateDate": "2013-11-27T14:26:53Z",
"EarliestShipDate": "2013-11-27T00:00:00Z",
"PurchaseDate": "2013-11-26T22:25:39Z",
"NumberOfItemsUnshipped": "0",
"AmazonOrderId": "205-8108202-4976362",
"NumberOfItemsShipped": "1",
"PaymentMethod": "Other"
}
]
},
"CreatedBefore": "2014-05-14T01:12:05Z"
},
"ResponseMetadata": {
"RequestId": "46f5c980-91e6-44d3-bc9d-668976855862"
},
"xmlns": "https://mws.amazonservices.com/Orders/2011-01-01"
}
CURRENT JS:
$(document).ready(function(){
$.get('functions/ListOrders.php', function(xml){
var newOrders = $.xml2json(xml);
$.each(newOrders.Orders.Order, function(index, value) {
console.log(value);
console.log(value.ShipmentServiceLevelCategory);
});
$('body').text(JSON.stringify(newOrders));
});
});
You are missing the first element of the JSON object:
Change
$.each(newOrders.Orders.Order, function(index, value) {
To
$.each(newOrders.ListOrdersResult.Orders.Order, function(index, value) {
Demo:
http://jsfiddle.net/9YU3H/