unable to access properties of objects inside array of JSON objects [closed] - javascript

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

Related

Accessing unique nested JSON array items

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)"]

Typescript array filtering not working

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

Javascript jquery json [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 6 years ago.
OK, so I have a json structure as follows.
Basically, what I want to do is loop over the json file and pull out the data if Country is equal to a specific value.
I'm sure this is pretty easy but i just can't work it out.
{
"Site ID": 19955,
"Hotels": "Ramada Salzburg City Centre",
"Stadt": "Salzburg",
"Country": "Austria",
"Region": "Central & Eastern Europe",
"Link DE": "",
"Link EN": "",
"Link TR": "",
"Lat": 47.8137521,
"Long": 13.044259,
"Image": "/Salzburg.jpg"
}
Use Array.prototype.filter
let austrianSites = sites.filter(site => site.Country === 'Austria')
Try
for (var i = 0, len = structure.length; i < len; i++) {
if (structure[i].Country === someValue) {
// do something here
}
}
How about checking if the JSON object has a property "Country" and if it does then output it. Hope it helps!
var jsonObject = {
"Site ID": 19955,
"Hotels": "Ramada Salzburg City Centre",
"Stadt": "Salzburg",
"Country": "Austria",
"Region": "Central & Eastern Europe",
"Link DE": "",
"Link EN": "",
"Link TR": "",
"Lat": 47.8137521,
"Long": 13.044259,
"Image": "wp-content/themes/wyndham-hotels/img/Salzburg.jpg"
}
for(var i in jsonObject){
if(jsonObject.hasOwnProperty("Country")){
var x = jsonObject.Country;
}
}
document.write("The Country is: " + x);
Please try this following:
var places = [{
"Site ID": 19955,
"Hotels": "Ramada Salzburg City Centre",
"Stadt": "Salzburg",
"Country": "Austria",
"Region": "Central & Eastern Europe",
"Link DE": "",
"Link EN": "",
"Link TR": "",
"Lat": 47.8137521,
"Long": 13.044259,
"Image": "/Salzburg.jpg"
}, {
"Site ID": 1211,
"Hotels": "test",
"Stadt": "Salzburg",
"Country": "NZ",
"Region": "Central & Eastern Europe",
"Link DE": "",
"Link EN": "",
"Link TR": "",
"Lat": 47.8137521,
"Long": 13.044259,
"Image": "/Salzburg.jpg"
}]
var filtered = places.filter(function(p) {
return p.Country === "NZ";
})
console.log(filtered);

Accessing objects in arrays inside objects in Angular

I am having quite a hard time accessing data from an api call and having it shown on Mapbox. I am able to have one marker shown on the map, while I should have 10 markers. I think I am doing something wrong with ng-repeat, but I am not sure what. Any help would be appreciated.
Here is a link to view the full JSON response from the API call http://jsonblob.com/55e734cee4b01190df374f1e
// index.html
<div ng-repeat="venue in bars.venues">
<marker lat="{{venue.location.lat}}" lng="{{venue.location.lng}}">
<h1>{{venue.name}}</h1>
<p>{{venue.contact}}</p>
<p>{{venue.location.formattedAddress}}</p>
</marker>
</div>
// app.js
$http.get(url)
.then(function (response) {
$scope.bars = response.data.response;
});
// sample data from api
{
"meta": {
"code": 200,
"requestId": "55e72707498e3d9a002d7bc4"
},
"response": {
"venues": [
{
"id": "42c1e480f964a520c4251fe3",
"name": "The View",
"contact": {
"phone": "4158961600",
"formattedPhone": "(415) 896-1600"
},
"location": {
"address": "55 4th St",
"crossStreet": "at Marriott Marquis",
"lat": 37.78510950100554,
"lng": -122.40469515323639,
"distance": 29,
"postalCode": "94103",
"cc": "US",
"city": "San Francisco",
"state": "CA",
"country": "United States",
"formattedAddress": [
"55 4th St (at Marriott Marquis)",
"San Francisco, CA 94103",
"United States"
]
},
"categories": [
{
"id": "4bf58dd8d48988d1d5941735",
"name": "Hotel Bar",
"pluralName": "Hotel Bars",
"shortName": "Hotel Bar",
"icon": {
"prefix": "https://ss3.4sqi.net/img/categories_v2/travel/hotel_bar_",
"suffix": ".png"
},
"primary": true
}
],
"verified": false,
"stats": {
"checkinsCount": 12634,
"usersCount": 9499,
"tipCount": 121
},
"url": "http://www.sfviewlounge.com",
"hasMenu": true,
"menu": {
"type": "Menu",
"label": "Menu",
"anchor": "View Menu",
"url": "https://foursquare.com/v/the-view/42c1e480f964a520c4251fe3/menu",
"mobileUrl": "https://foursquare.com/v/42c1e480f964a520c4251fe3/device_menu"
},
So I figured out why only one marker was showing. I was previously using angular google maps and had ngMaps as a module. After I deleted it, all my markers showed.

jQuery .each display array data - cannot work it out

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/

Categories