Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I need to go through each hotel key and go inside rates to retrieve some info, how could I get values of them inside this JSON on JavaScript:
[
{
"auditData": {
"processTime": "1545",
"timestamp": "2016-04-08 04:33:17.145",
"requestHost": "66.226.74.194",
"serverId": "sa37AUX3ROLBLIS.env",
"environment": "[int]",
"release": "2cb1bad878d2195c9b508e2007ef96616007dacb",
"internal": "bz66k2etuxrt5q5h2zyf3jf6|MX|03|HA|1|3|0|1|3|N|||||||||1"
},
"hotel": {
"checkIn": "2016-04-11",
"checkOut": "2016-04-12",
"code": 87399,
"name": "Premier",
"categoryCode": "3EST",
"categoryName": "3 ESTRELLAS",
"destinationCode": "MDF",
"destinationName": "Ciudad de Mexico",
"zoneCode": 10,
"zoneName": "Downtown",
"latitude": "19.431353",
"longitude": "-99.156457",
"rooms": [
{
"code": "DBL.2D",
"name": "DOBLE DOS CAMAS DOBLES",
"rates": [
{
"rateKey": "20160411|20160412|W|71|87399|DBL.2D|CGW-TODOS1|BB||1~2~1|2|N#-644903865",
"rateClass": "NOR",
"rateType": "BOOKABLE",
"net": "687.31",
"discount": "111.89",
"discountPCT": "14.00",
"sellingRate": "799.20",
"rateComments": "Incluye desayuno americano para adulto y menor\nel hotel no cuenta con aire acondicionado ",
"paymentType": "AT_WEB",
"packaging": false,
"boardCode": "BB",
"boardName": "ALOJAMIENTO Y DESAYUNO",
"cancellationPolicies": [
{
"amount": "799.20",
"from": "2016-04-08T23:59:00-05:00"
}
],
"rateBreakDown": {
"rateDiscounts": [
{
"code": "DN",
"name": "Descuento Niño",
"amount": "-281.68"
}
]
},
"rooms": 1,
"adults": 2,
"children": 1,
"childrenAges": "2",
"offers": [
{
"code": "9001",
"name": "Descuento niños",
"amount": "-281.68"
}
]
}
]
}
],
"totalSellingRate": "799.20",
"totalNet": "687.31",
"currency": "MXN"
}
},
{
"auditData": {
"processTime": "1543",
"timestamp": "2016-04-08 04:33:19.469",
"requestHost": "66.226.74.194",
"serverId": "sa3RKSJACHXE79K.env",
"environment": "[int]",
"release": "2cb1bad878d2195c9b508e2007ef96616007dacb",
"internal": "bz66k2etuxrt5q5h2zyf3jf6|MX|03|HA|1|3|0|3|3|N|||||||||1"
},
"hotel": {
"checkIn": "2016-04-11",
"checkOut": "2016-04-12",
"code": 87399,
"name": "Premier",
"categoryCode": "3EST",
"categoryName": "3 ESTRELLAS",
"destinationCode": "MDF",
"destinationName": "Ciudad de Mexico",
"zoneCode": 10,
"zoneName": "Downtown",
"latitude": "19.431353",
"longitude": "-99.156457",
"rooms": [
{
"code": "SGL.DB",
"name": "INDIVIDUAL CAMA DOBLE",
"rates": [
{
"rateKey": "20160411|20160412|W|71|87399|SGL.DB|CGW-TODOS1|BB||1~1~1|5|N#-644903865",
"rateClass": "NOR",
"rateType": "BOOKABLE",
"net": "687.31",
"discount": "111.89",
"discountPCT": "14.00",
"sellingRate": "799.20",
"rateComments": "Incluye desayuno americano para adulto y menor\nel hotel no cuenta con aire acondicionado ",
"paymentType": "AT_WEB",
"packaging": false,
"boardCode": "BB",
"boardName": "ALOJAMIENTO Y DESAYUNO",
"cancellationPolicies": [
{
"amount": "799.20",
"from": "2016-04-08T23:59:00-05:00"
}
],
"rateBreakDown": {
"rateDiscounts": [
{
"code": "DN",
"name": "Descuento Niño",
"amount": "-641.98"
}
]
},
"rooms": 1,
"adults": 1,
"children": 1,
"childrenAges": "5",
"offers": [
{
"code": "9001",
"name": "Descuento niños",
"amount": "-641.98"
}
]
}
]
}
],
"totalSellingRate": "799.20",
"totalNet": "687.31",
"currency": "MXN"
}
}
]
I was trying to use for (var key in data), where data is the JSON response from AJAX.
It's an array. You should iterate using a normal for loop, like
for(var i = 0; i < data.length;i++) {
var rooms = data[i].hotel.rooms
for(var j = 0; j < rooms.length; j++) {
var rates = rooms.rates .. //do something with rates, it's also an array
}
}
Use a each loop each time you see a [] the first character in the string is bracket so we do a each we select the child in our case "hotel" using dot notation v.hotel,v.hotel doesn't start with a bracket so we don't need a loop,we go down in the json object until we reach the rates key where we see another braket so we loop and select the child element in our case the rateKey
var obj =[
{
"auditData": {
"processTime": "1545",
"timestamp": "2016-04-08 04:33:17.145",
"requestHost": "66.226.74.194",
"serverId": "sa37AUX3ROLBLIS.env",
"environment": "[int]",
"release": "2cb1bad878d2195c9b508e2007ef96616007dacb",
"internal": "bz66k2etuxrt5q5h2zyf3jf6|MX|03|HA|1|3|0|1|3|N|||||||||1"
},...];
$.each(obj, function(i, v) {
$.each(v.hotel.rooms, function(i1, v1) {
$.each(v1.rates, function(i2, v2) {
console.log(v2.rateKey);
});
})
});
https://jsfiddle.net/78cpwq5g/
Use the Json object.
If suppose the values are stored in JsonObject.
And some values you may want to retrieve.
Eg:- "code": 87399,
"name": "Premier",
"categoryCode": "3EST",
"categoryName": "3 ESTRELLAS",
"destinationCode": "MDF",
"destinationName": "Ciudad de Mexico",
$(JsonObject).each(function(){
$(this).hotel.code;
$(this).hotel.name;
})
Related
I have two separate json files that are the response provided from an online api service and will hold the informations about the last two football season of Italian Serie A.
I want to use the unique team id and the result of the match to create a dataset to use with brain.js, what's the best way to achive this?
I've tried to unify the files by copying the content of the second file into the first ove but I will then have two matches array and other duplied fields and I'm not sure on how to process data to ingest into brain.js
{
"filters": {
"season": 2021
},
"resultSet": {
"count": 380,
"first": "2021-08-21",
"last": "2022-05-22",
"played": 380
},
"competition": {
"id": 2019,
"name": "Serie A",
"code": "SA",
"type": "LEAGUE",
"emblem": "https://crests.football-data.org/SA.png"
},
"matches": [
{
"area": {
"id": 2114,
"name": "Italy",
"code": "ITA",
"flag": "https://crests.football-data.org/784.svg"
},
"competition": {
"id": 2019,
"name": "Serie A",
"code": "SA",
"type": "LEAGUE",
"emblem": "https://crests.football-data.org/SA.png"
},
"season": {
"id": 757,
"startDate": "2021-08-21",
"endDate": "2022-05-22",
"currentMatchday": 38,
"winner": null
},
"id": 333779,
"utcDate": "2021-08-21T16:30:00Z",
"status": "FINISHED",
"matchday": 1,
"stage": "REGULAR_SEASON",
"group": null,
"lastUpdated": "2022-06-25T08:20:15Z",
"homeTeam": {
"id": 108,
"name": "FC Internazionale Milano",
"shortName": "Inter",
"tla": "INT",
"crest": "https://crests.football-data.org/108.png"
},
"awayTeam": {
"id": 107,
"name": "Genoa CFC",
"shortName": "Genoa",
"tla": "GEN",
"crest": "https://crests.football-data.org/107.svg"
},
"score": {
"winner": "HOME_TEAM",
"duration": "REGULAR",
"fullTime": {
"home": 4,
"away": 0
},
"halfTime": {
"home": 2,
"away": 0
}
},
"odds": {
"msg": "Activate Odds-Package in User-Panel to retrieve odds."
},
"referees": [
{
"id": 11336,
"name": "Valerio Marini",
"type": "REFEREE",
"nationality": "Italy"
}
]
},{ ... } //
],
// here I will have the other season
"filters": {
"season": 2020
},
"resultSet": {
"count": 380,
"first": "2021-08-21",
"last": "2022-05-22",
"played": 380
},
"competition": {
"id": 2019,
"name": "Serie A",
"code": "SA",
"type": "LEAGUE",
"emblem": "https://crests.football-data.org/SA.png"
},
"matches": [
{...}]
}
At the momen I've used this code on the json I have created to have training data.
const dataset = Object.values(samples.matches).map( (match) => {
let result
switch( match.score.winner ) {
case 'HOME_TEAM':
result = 0
break;
case 'AWAY_TEAM':
result = 1
break;
case 'DRAW':
result = 2
break;
}
return {
homeTeam: match.homeTeam.id,
awayTeam: match.awayTeam.id,
matchResult: result
}
})
//console.log( dataset )
const trainingData = dataset.map( (data) => {
return {
input: [ data.homeTeam, data.awayTeam ],
output: [ data.matchResult ]
}
})
this is what the data I'm using with brain will look
{ homeTeam: 112, awayTeam: 1106, matchResult: 2 },
{ homeTeam: 472, awayTeam: 113, matchResult: 1 },
{ homeTeam: 584, awayTeam: 98, matchResult: 1 },
{ homeTeam: 99, awayTeam: 107, matchResult: 2 },
{ homeTeam: 471, awayTeam: 1106, matchResult: 0 },
{ homeTeam: 472, awayTeam: 488, matchResult: 0 },
where 0 is when home team win, 1 when away team win and 2 if draw, but I need to have a better solution for handle this case.
I can't seem to extract the nested data I'm getting from a Shopify orders/create webhook and write it to a spreadsheet.
I was able to go down one level by using shift() like this var lineItems = myData.line_items.shift(); but the next level comes back as [Ljava.lang.Object;#1746c8f9
Though the first level of the object does come back readable.
Here is my code:
function doPost(e) {
var myData = JSON.parse(e.postData.contents);
var lineItems = myData.line_items.shift();
var prop = lineItems.properties;
var sheet = SpreadsheetApp.getActiveSheet();
sheet.appendRow([lineItems,prop]);
}
Here is how Shopify documentation says the webhook response will be: (I took out the irrelevant data to shorten)
I need to extract the line_items data and specifically the properties object (though in this example it is blank thats because it reflects custom properties entered by user)
{
"id": 820982911946154508,
"email": "jon#doe.ca",
"order_number": 1234,
"order_status_url": "https:\/\/apple.myshopify.com\/690933842\/orders\/123456abcd\/authenticate?key=abcdefg",
"line_items": [
{
"id": 866550311766439020,
"variant_id": 808950810,
"title": "IPod Nano - 8GB",
"quantity": 1,
"sku": "IPOD2008PINK",
"variant_title": null,
"vendor": null,
"fulfillment_service": "manual",
"product_id": 632910392,
"requires_shipping": true,
"taxable": true,
"gift_card": false,
"name": "IPod Nano - 8GB",
"variant_inventory_management": "shopify",
"properties": [
],
"product_exists": true,
"fulfillable_quantity": 1,
"grams": 567,
"price": "199.00",
"total_discount": "0.00",
"fulfillment_status": null,
"price_set": {
"shop_money": {
"amount": "199.00",
"currency_code": "USD"
},
"presentment_money": {
"amount": "199.00",
"currency_code": "USD"
}
},
"total_discount_set": {
"shop_money": {
"amount": "0.00",
"currency_code": "USD"
},
"presentment_money": {
"amount": "0.00",
"currency_code": "USD"
}
},
"discount_allocations": [
],
"duties": [
],
"admin_graphql_api_id": "gid:\/\/shopify\/LineItem\/866550311766439020",
"tax_lines": [
]
},
{
"id": 141249953214522974,
"variant_id": 808950810,
"title": "IPod Nano - 8GB",
"quantity": 1,
"sku": "IPOD2008PINK",
"variant_title": null,
"vendor": null,
"fulfillment_service": "manual",
"product_id": 632910392,
"requires_shipping": true,
"taxable": true,
"gift_card": false,
"name": "IPod Nano - 8GB",
"variant_inventory_management": "shopify",
"properties": [
],
"product_exists": true,
"fulfillable_quantity": 1,
"grams": 567,
"price": "199.00",
"total_discount": "5.00",
"fulfillment_status": null,
"price_set": {
"shop_money": {
"amount": "199.00",
"currency_code": "USD"
},
"presentment_money": {
"amount": "199.00",
"currency_code": "USD"
}
},
"total_discount_set": {
"shop_money": {
"amount": "5.00",
"currency_code": "USD"
},
"presentment_money": {
"amount": "5.00",
"currency_code": "USD"
}
},
"discount_allocations": [
{
"amount": "5.00",
"discount_application_index": 0,
"amount_set": {
"shop_money": {
"amount": "5.00",
"currency_code": "USD"
},
"presentment_money": {
"amount": "5.00",
"currency_code": "USD"
}
}
}
],
"duties": [
],
"admin_graphql_api_id": "gid:\/\/shopify\/LineItem\/141249953214522974",
"tax_lines": [
]
}
],
"total_tip_received": "0.0",
"original_total_duties_set": null,
Convert prop to a string using whatever method you prefer.
sheet.appendRow([lineItems,JSON.stringify(prop)]);
You may also want to stringify lineItems.
I was able to figure how to access the properties. If someone has a better way please answer too.
Also please see full code in this question: Quicken google apps script so I can return success response within Shopify 5 second limit
var data = JSON.parse(e.postData.contents);
var l = data.line_items.length;
for (var i=0;i<l;i++){
var prop = data.line_items[i].properties;
var pdf = prop.find(function(x) {if(x.name == "_pdf") return x});
if (!pdf){pdf = "Prop not found";}else{pdf = pdf.value};
I have the JSON like
var resultJSON = `{
"data": {
"total": 1,
"list_name": "title",
"title": {
"id": 53,
"name": "Sonu",
"mobileNo": "6543213456",
"address": "Greeny Pathway",
"city": "NewYork",
"mode": "Weekly",
"duration": "15",
"qty": null
},
"download": [{
"time": "16789042",
"date": "26 - 01 - 2020"
}]
}
}`;
I expect the output:
{
"total": "1",
"list_name": "title",
"name": "sonu",
"mobileno": "6543213456"
}
Here "list_name": "title" is dynamic, sometimes it will come "list_name": "book", based on that above mentioned response I want to get.
Something like this? I had to fix your invalid JSON
You can make it more clever if you study https://javascript.info/destructuring-assignment in depth
const resultJSON = `{
"data": {
"total": 1,
"list_name": "title",
"title": {
"id": 53,
"name": "Sonu",
"mobileNo": "6543213456",
"address": "Greeny Pathway",
"city": "NewYork",
"mode": "Weekly",
"duration": "15",
"qty": null
},
"download": [{
"time": "16789042",
"date": "26-01-2020"
}]
}
}`
const data = JSON.parse(resultJSON).data
const content = data[data.list_name];
let newObj = {}
newObj["total"] = data["total"];
newObj["list_name"] = data["list_name"];
newObj["name"] = content["name"];
newObj["mobileNo"] = content["mobileNo"];
console.log(newObj)
Actually i want to add "is_promoted" field in the response according to the result of elastic search if the "doc_count" is 1 then i have to fetch the id of the property and "is_promoted" flag from the actual result(Which you can see at the question).Its like a post filter in the elastic search. but i want add condition in the post filter. please see the current and expected output.
And below is the current output of the elastic query
{
"total_records": 32392,
"fetched_records": 3845,
"result": [
{
"key": "dp3w",
"doc_count": 343,
"centroid": {
"location": {
"lat": 41.919059987131064,
"lon": -87.71653202438385
},
"count": 343
}
},
{
"key": "djvw",
"doc_count": 1,
"centroid": {
"location": {
"lat": 33.49416188221888,
"lon": -82.0443208285174
},
"count": 1
}
},
{
"key": "9qhs",
"doc_count": 1,
"centroid": {
"location": {
"lat": 34.52696419113244,
"lon": -117.29711956000672
},
"count": 1
}
}
]
}
So i want to add field "is_promoted" if the "doc_count" is 1 and below is the expected output
{
"total_records": 32392,
"fetched_records": 3845,
"result": [
{
"key": "dp3w",
"doc_count": 343,
"centroid": {
"location": {
"lat": 41.919059987131064,
"lon": -87.71653202438385
},
"count": 343
}
},
{
"key": "djvw",
"doc_count": 1,
"is_promoted":true,
"centroid": {
"location": {
"lat": 33.49416188221888,
"lon": -82.0443208285174
},
"count": 1
}
},
{
"key": "9qhs",
"doc_count": 1,
"is_promoted":true,
"centroid": {
"location": {
"lat": 34.52696419113244,
"lon": -117.29711956000672
},
"count": 1
}
}
]
}
I used aggregation for that.
query.bool.minimum_should_match = 1;
aggQuery.zoomedin = {
filter: {
geo_bounding_box: {
location: {
top_left: {
lat: params.geo_bounding_box.location.nw.lat,
lon: params.geo_bounding_box.location.nw.lng
},
bottom_right: {
lat: params.geo_bounding_box.location.se.lat,
lon: params.geo_bounding_box.location.se.lng
}
}
}
},
aggregations: {
result: {
geohash_grid: {
field: "location",
precision: zoomLevel
},
"aggs": {
"centroid": {
"geo_centroid": { "field": "location" }
}
}
}
}
Below is the record structure in my elastic search. I hope it will help you to understand the senario
"hits": {
"total": 7967,
"max_score": 1,
"hits": [
{
"_index": "biproxi-test",
"_type": "listings",
"_id": "5126",
"_score": 1,
"_source": {
"address_line1": "Brandon Town Center Drive",
"address_line2": "USA",
"building_class": null,
"building_type": null,
"built_year": null,
"cap_rate": null,
"category": 1,
"city": "Brandon",
"country": "United States",
"county": "Hillsborough",
"floor_location": null,
"inplace_occupancy": null,
"land_size": 3,
"lease_type_id": null,
"lease_type": null,
"listing_group": "Retail",
"listing_type": [
1
],
"location": {
"lat": 27.937159,
"lon": -82.327498
},
"no_of_units": null,
"postal_code": "33511",
"price": 2185000,
"renovated_year": null,
"square_feet": null,
"state": "Florida",
"state_code": "FL",
"title": "3+- Acres at Brandon Town Center",
"status": 2,
"listing_image": "https://biproxi.s3.amazonaws.com/image/listing/5126/caf39154-fb42-483f-9320-9e9c394be66b.jpg",
"seller_id": "113157245308689129523",
"is_promoted": false
}
}, {
"_index": "biproxi-test",
"_type": "listings",
"_id": "5213",
"_score": 1,
"_source": {
"address_line1": "1909 N. Columbia Street",
"address_line2": "USA",
"building_class": null,
"building_type": null,
"built_year": "1996",
"cap_rate": null,
"category": 2,
"city": "Milledgeville",
"country": "United States",
"county": "Baldwin",
"floor_location": null,
"inplace_occupancy": null,
"land_size": null,
"lease_type_id": null,
"lease_type": null,
"listing_group": "Retail",
"listing_type": [
1
],
"location": {
"lat": 33.1086,
"lon": -83.25388
},
"no_of_units": null,
"postal_code": "31061",
"price": null,
"renovated_year": null,
"square_feet": null,
"state": "Georgia",
"state_code": "GA",
"title": "Milledge Village - 1 Space Remaining",
"status": 2,
"listing_image": "https://biproxi.s3.amazonaws.com/image/listing/5213/33d1cd5b-11a1-427d-8948-2e2db3d8e7f2.jpg",
"seller_id": "113157245308689129523",
"is_promoted": false
}
}
}]}
Okay, so, from the discussion in the direct comments under your OP I understand that you only want to add is_promoted field to some of the objects in the result array of the ES response, according to a certain condition.
What you need to do is very simple: loop through the result array, check the condition for each object and add the property.
for (const obj of elasticSearchResult.result) {
if (+obj.doc_count <= 1) {
obj['is_promoted'] = true;
}
}
I add the + sign in front of the obj.doc_count to ensure it's parsed to int and thus conducting a proper conditional comparison. The is_promoted property is added as an array key to ensure there are no compile or runtime errors of the sort of Property does not exist, since we create a new property in the object.
I don't know why do you use this aggregation functionality. You problem is purely JavaScript related and has nothing to do with ES or Node.js in particular.
P.S. This solution is based on the fact I understand your question correctly. Otherwise, please extend or improve your OP.
{
"name": "English Premier League 2015/16",
"rounds": [
{
"name": "Play-Off um 1 Premierleague-Platz:",
"matches": [
{
"date": "2015-08-08",
"team1": {
"key": "manutd",
"name": "Manchester United",
"code": "MUN"
},
"team2": {
"key": "tottenham",
"name": "Tottenham Hotspur",
"code": "TOT"
},
"score1": 1,
"score2": 0
},
{
"date": "2015-08-08",
"team1": {
"key": "bournemouth",
"name": "Bournemouth",
"code": "BOU"
},
"team2": {
"key": "astonvilla",
"name": "Aston Villa",
"code": "AVL"
},
"score1": 0,
"score2": 1
},
{
"date": "2015-08-08",
"team1": {
"key": "everton",
"name": "Everton",
"code": "EVE"
},
"team2": {
"key": "watford",
"name": "Watford",
"code": "WAT"
},
"score1": 2,
"score2": 2
},
{
"date": "2015-08-08",
"team1": {
"key": "leicester",
"name": "Leicester City",
"code": "LEI"
},
"team2": {
"key": "sunderland",
"name": "Sunderland",
"code": "SUN"
},
"score1": 4,
"score2": 2
},
{
"date": "2015-08-08",
"team1": {
"key": "norwich",
"name": "Norwich",
"code": "NOR"
},
"team2": {
"key": "crystalpalace",
"name": "Crystal Palace",
"code": "CRY"
},
"score1": 1,
"score2": 3
},
{
"date": "2015-08-08",
"team1": {
"key": "chelsea",
"name": "Chelsea",
"code": "CHE"
},
"team2": {
"key": "swansea",
"name": "Swansea",
"code": "SWA"
},
"score1": 2,
"score2": 2
},
{
"date": "2015-08-09",
"team1": {
"key": "arsenal",
"name": "Arsenal",
"code": "ARS"
},
"team2": {
"key": "westham",
"name": "West Ham United",
"code": "WHU"
},
"score1": 0,
"score2": 2
},
{
"date": "2015-08-09",
"team1": {
"key": "newcastle",
"name": "Newcastle United",
"code": "NEW"
},
"team2": {
"key": "southampton",
"name": "Southampton",
"code": "SOU"
},
"score1": 2,
"score2": 2
},
{
"date": "2015-08-09",
"team1": {
"key": "stoke",
"name": "Stoke City",
"code": "STK"
},
"team2": {
"key": "liverpool",
"name": "Liverpool",
"code": "LIV"
},
"score1": 0,
"score2": 1
},
{
"date": "2015-08-10",
"team1": {
"key": "westbrom",
"name": "West Bromwich Albion",
"code": "WBA"
},
"team2": {
"key": "mancity",
"name": "Manchester City",
"code": "MCI"
},
"score1": 0,
"score2": 3
}
]
}
]
}
I want to log all the matches which are inside matches array . But i can't seem to access them because there are objects ,arrays ,more arrays and more objects nested inside one another. Kinda confused.please help explaining how to access elements in such situation. Which loops to use, what to do in case of looping through objects and so on. Hope I have explained my problem quite elaborately.
You can try this this code here:
const data = {"name":"English Premier League 2015/16","rounds":[{"name":"Play-Off um 1 Premierleague-Platz:","matches":[{"date":"2015-08-08","team1":{"key":"manutd","name":"Manchester United","code":"MUN"},"team2":{"key":"tottenham","name":"Tottenham Hotspur","code":"TOT"},"score1":1,"score2":0},{"date":"2015-08-08","team1":{"key":"bournemouth","name":"Bournemouth","code":"BOU"},"team2":{"key":"astonvilla","name":"Aston Villa","code":"AVL"},"score1":0,"score2":1},{"date":"2015-08-08","team1":{"key":"everton","name":"Everton","code":"EVE"},"team2":{"key":"watford","name":"Watford","code":"WAT"},"score1":2,"score2":2},{"date":"2015-08-08","team1":{"key":"leicester","name":"Leicester City","code":"LEI"},"team2":{"key":"sunderland","name":"Sunderland","code":"SUN"},"score1":4,"score2":2},{"date":"2015-08-08","team1":{"key":"norwich","name":"Norwich","code":"NOR"},"team2":{"key":"crystalpalace","name":"Crystal Palace","code":"CRY"},"score1":1,"score2":3},{"date":"2015-08-08","team1":{"key":"chelsea","name":"Chelsea","code":"CHE"},"team2":{"key":"swansea","name":"Swansea","code":"SWA"},"score1":2,"score2":2},{"date":"2015-08-09","team1":{"key":"arsenal","name":"Arsenal","code":"ARS"},"team2":{"key":"westham","name":"West Ham United","code":"WHU"},"score1":0,"score2":2},{"date":"2015-08-09","team1":{"key":"newcastle","name":"Newcastle United","code":"NEW"},"team2":{"key":"southampton","name":"Southampton","code":"SOU"},"score1":2,"score2":2},{"date":"2015-08-09","team1":{"key":"stoke","name":"Stoke City","code":"STK"},"team2":{"key":"liverpool","name":"Liverpool","code":"LIV"},"score1":0,"score2":1},{"date":"2015-08-10","team1":{"key":"westbrom","name":"West Bromwich Albion","code":"WBA"},"team2":{"key":"mancity","name":"Manchester City","code":"MCI"},"score1":0,"score2":3}]}]};
data.rounds.forEach((round) => {
round.matches.forEach((match) => {
console.log(`Results ${ match.score1 } | ${ match.score2 }`);
})
});
Basically you're using a mixture of array and object references.
You use your object references (data.rounds or round.matches) to get to specific properties on your object. Then you can you array functions (.forEach() which you can read about here) to access the objects in each array. Then you just access the properties of those sub objects.
Hope this helps.
Building on Phil's comment, something like this should help you iterate through the matches and do something with each.
obj.rounds[0].matches.forEach(match => {
console.log(match);
})
The snippet shared is actually a object. Inside this object there is a key by name rounds, which is again array of objects.
So data.rounds will give the value which is an array.
Inside this array there is array of matches. But data.rounds is array of only one object. Hence data.rounds[0] will allow to access it's value. [0] being the index, since in array the first element is at 0 index & data.rounds[0].matches will give the array of matches
var data = {
"name": "English Premier League 2015/16",
"rounds": [{
"name": "Play-Off um 1 Premierleague-Platz:",
"matches": [
//other objects
]
}
console.log(data.rounds[0].matches)
DEMO
I guest that your data is structured in a JSON that you are going to decoded using the json_decode function like this:
$myMatches = json_decode($yourJSON);
After that JSON gets converted into an object you can access any property by following the following rules:
Every opening curly bracket on the JSON gets converted into an object, and you will have to use the arrow syntax like this: $myMatches->attribute
For example, imagine an object "$person" with the following structure:
{
"name": "manutd",
"lastname": "Manchester United",
"phone": "MUN"
}
To print the name you will have to do:
echo $person->name;
On the other hand, every normal bracket gets transformed into an array and you have to use brackets to access that information (like any other array), like this: $myMatches['attribute']
For example that same person but now with array syntax:
[
"name": "manutd",
"lastname": "Manchester United",
"phone": "MUN"
]
To print the name you will have to do:
echo $person['name'];
Now, for your question in particular
That said, if you want to print the date of the first round of the first match, you will have to do:
echo $myMatches->rounds[0]->matches[0]->date;
I have prepared this functions for your disposal:
//This function returns all the matches in one tournament round
function getMatchesOfRound($myMatches, $roundNumber)
{
return $myMatches->rounds[$roundNumber]->matches;
}
//This function returns all the matches played by $teamKey
function getAllMatchesOfTeam($myMatches, $teamKey){
$matches = [];
foreach($myMatches->rounds as $rounds)
foreach($rounds->matches as $match)
if($match->team1->key == $teamKey || $match->team2->key == $teamKey) $matches[] = $match;
return $matches;
}
//this function determines the winner of a given match and returns the $teamKey
function getWinerFromMatch($match){
if($match->score1 > $match->score2) return $match->team1;
else if($match->score1 < $match->score2) return $match->team2;
else return null;
}
//This function returns all matches won by $teamKey
function getAllMatchesOfTeam($myMatches, $teamKey){
$matches = [];
foreach($myMatches->rounds as $rounds)
foreach($rounds->matches as $match)
if(getWinerFromMatch($match) == $teamKey) $matches[] = $match;
return $matches;
}
//This function returns all ties
function getAllMatchesOfTeam($myMatches, $teamKey){
$matches = [];
foreach($myMatches->rounds as $rounds)
foreach($rounds->matches as $match)
if(getWinerFromMatch($match) == null) $matches[] = $match;
return $matches;
}
You get the idea, I hope this helps. I have not tested the code, maybe it has minor sytax errors.
result = {
"name": "English Premier League 2015/16",
"rounds": [
{
"name": "Play-Off um 1 Premierleague-Platz:",
"matches": [
{
"date": "2015-08-08",
"team1": {
"key": "manutd",
"name": "Manchester United",
"code": "MUN"
},
"team2": {
"key": "tottenham",
"name": "Tottenham Hotspur",
"code": "TOT"
},
"score1": 1,
"score2": 0
},
{
"date": "2015-08-08",
"team1": {
"key": "bournemouth",
"name": "Bournemouth",
"code": "BOU"
},
"team2": {
"key": "astonvilla",
"name": "Aston Villa",
"code": "AVL"
},
"score1": 0,
"score2": 1
},
{
"date": "2015-08-08",
"team1": {
"key": "everton",
"name": "Everton",
"code": "EVE"
},
"team2": {
"key": "watford",
"name": "Watford",
"code": "WAT"
},
"score1": 2,
"score2": 2
},
{
"date": "2015-08-08",
"team1": {
"key": "leicester",
"name": "Leicester City",
"code": "LEI"
},
"team2": {
"key": "sunderland",
"name": "Sunderland",
"code": "SUN"
},
"score1": 4,
"score2": 2
},
{
"date": "2015-08-08",
"team1": {
"key": "norwich",
"name": "Norwich",
"code": "NOR"
},
"team2": {
"key": "crystalpalace",
"name": "Crystal Palace",
"code": "CRY"
},
"score1": 1,
"score2": 3
},
{
"date": "2015-08-08",
"team1": {
"key": "chelsea",
"name": "Chelsea",
"code": "CHE"
},
"team2": {
"key": "swansea",
"name": "Swansea",
"code": "SWA"
},
"score1": 2,
"score2": 2
},
{
"date": "2015-08-09",
"team1": {
"key": "arsenal",
"name": "Arsenal",
"code": "ARS"
},
"team2": {
"key": "westham",
"name": "West Ham United",
"code": "WHU"
},
"score1": 0,
"score2": 2
},
{
"date": "2015-08-09",
"team1": {
"key": "newcastle",
"name": "Newcastle United",
"code": "NEW"
},
"team2": {
"key": "southampton",
"name": "Southampton",
"code": "SOU"
},
"score1": 2,
"score2": 2
},
{
"date": "2015-08-09",
"team1": {
"key": "stoke",
"name": "Stoke City",
"code": "STK"
},
"team2": {
"key": "liverpool",
"name": "Liverpool",
"code": "LIV"
},
"score1": 0,
"score2": 1
},
{
"date": "2015-08-10",
"team1": {
"key": "westbrom",
"name": "West Bromwich Albion",
"code": "WBA"
},
"team2": {
"key": "mancity",
"name": "Manchester City",
"code": "MCI"
},
"score1": 0,
"score2": 3
}
]
}
]
};
for ( let i=0, totalRounds = result.rounds.length; i < totalRounds; i++) {
let round = result.rounds[i];
console.log( round.name );
for ( let j=0, totalMatches = round.matches.length; j < totalMatches; j++ ) {
let match = round.matches[j];
console.log( match.date + ': ' + match.team1.name + " " + match.score1 + " - " + match.team2.name + " " + match.score2)
}
}
You can fetch all the matches in a variable then iterate over it using any loop.
If there is only 1 round then this will do the task.
var matches = object.rounds[0]. matches;
for(var match in matches){
console.log(match);
}
If there more rounds then you to first iterate over rounds and inside that loop fetch all the matches in that particular round.
for(var round in object.rounds){
var matches = round.matches;
for(var prop in matches){
console.log(prop);
}
}