prepare dataset from json to train RNN in brain.js and node - javascript

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.

Related

How can i calculate the rating in the rating array and still return it as a response

This is the sample JSON response from the Backend, the rating is in ratings array and the value is rating, so I want to calculate the average rating for each course and still return it as a response to frontend,
I tried using Object.Assign() but is worked well when i am fetching just one course but when i am fetching all courses, it doesn't work.
please i need help
{
"message": "Fetched successfully",
"status": "Success",
"statusCode": 200,
"data": {
"items": [
{
"id": 210,
"courseUuid": "93b760a7-505e-41bf-b57e-d84ecf53255f",
"userId": 2,
"title": "Complete Angularzero to hero",
"imageUrl": "https://our-akademy-uploads.s3.eu-west-1.amazonaws.com/courses/1655654436946-f02118c8-e3e9-44e5-8913-48d4f45cd816.png",
"slugUrl": "Complete-Angularzero-to-hero-19-06-2022-93b760a7-505e-41bf-b57e-d84ecf53255f",
"amount": "50,600",
"averageRating": "11.5",
"createdAt": "2022-06-19T16:00:43.009Z",
"updatedAt": "2022-06-19T23:27:46.073Z",
"user": {
"id": 2,
"userUuid": "b1f8def8-aa1d-4a57-b743-174a6ee738ec",
"email": "jessika76#hotmail.com",
"nawisNumber": "NAWIS/2022/54682884"
},
"category": {
"id": 1,
"categoryUuid": "3a4def94-dd1a-451c-8f84-476096203710",
"name": "Front-End Development",
"slugUrl": "Front-End-Development-18-06-2022-ec0a7634-b710-4723-b646-4cde33d3d15a"
},
"duration": {
"id": 23,
"durationUuid": "3500b0d0-8d98-46d6-80d8-6363c09e887c",
"duration": "5 Months"
},
"enrollments": [
{
"id": 1,
"paymentStatus": "Not Completed",
"createdAt": "2022-06-19T16:04:22.375Z",
"user": {
"id": 3,
"userUuid": "ad0b0ad4-368d-4f09-ae99-80d2bcaed3d6",
"email": "damion.jacobs84#yahoo.com",
"nawisNumber": "NAWIS/2022/12758991"
}
},
{
"id": 2,
"paymentStatus": "Not Completed",
"createdAt": "2022-06-19T16:07:37.059Z",
"user": {
"id": 6,
"userUuid": "cbfbc6a7-dfd7-4f74-a545-a1423ccdb0f3",
"email": "olaf_bailey#hotmail.com",
"nawisNumber": "NAWIS/2022/11177867"
}
}
],
"ratings": [
{
"id": 1,
"rating": 2,
"review": "some text here",
"createdAt": "2022-06-19T16:04:40.339Z",
"user": {
"id": 3,
"userUuid": "ad0b0ad4-368d-4f09-ae99-80d2bcaed3d6",
"email": "damion.jacobs84#yahoo.com"
}
},
{
"id": 2,
"rating": 5,
"review": "some text here",
"createdAt": "2022-06-19T16:07:23.798Z",
"user": {
"id": 6,
"userUuid": "cbfbc6a7-dfd7-4f74-a545-a1423ccdb0f3",
"email": "olaf_bailey#hotmail.com"
}
}
]
},
{
"id": 208,
"courseUuid": "16855bd6-dd18-420a-8611-bc77bbda818c",
"userId": 2,
"title": "Complete Vuejs zero to hero",
"imageUrl": "https://our-akademy-uploads.s3.eu-west-1.amazonaws.com/courses/1655653347091-cfee6022-0d3a-43e2-b780-986eda2607ed.png",
"slugUrl": "undefined-19-06-2022-16855bd6-dd18-420a-8611-bc77bbda818c",
"amount": "0",
"averageRating": "0",
"createdAt": "2022-06-19T15:42:30.273Z",
"updatedAt": "2022-06-19T15:53:07.726Z",
"user": {
"id": 2,
"userUuid": "b1f8def8-aa1d-4a57-b743-174a6ee738ec",
"email": "jessika76#hotmail.com",
"nawisNumber": "NAWIS/2022/54682884"
},
"category": {
"id": 1,
"categoryUuid": "3a4def94-dd1a-451c-8f84-476096203710",
"name": "Front-End Development",
"slugUrl": "Front-End-Development-18-06-2022-ec0a7634-b710-4723-b646-4cde33d3d15a"
},
"duration": {
"id": 23,
"durationUuid": "3500b0d0-8d98-46d6-80d8-6363c09e887c",
"duration": "5 Months"
},
"enrollments": [],
"ratings": []
},
{
"id": 207,
"courseUuid": "bdb3ee71-0c0b-41d8-9049-5fa6a2a230f3",
"userId": 2,
"title": "Complete Vuejs zero to hero",
"imageUrl": "https://our-akademy-uploads.s3.eu-west-1.amazonaws.com/courses/1655653325613-dda17c5c-2a4a-435a-99cb-ad28ea01bbb0.png",
"slugUrl": "Complete-Vuejs-zero-to-hero-19-06-2022-bdb3ee71-0c0b-41d8-9049-5fa6a2a230f3",
"amount": "50,600",
"averageRating": "0",
"createdAt": "2022-06-19T15:42:12.687Z",
"updatedAt": "2022-06-19T15:42:12.687Z",
"user": {
"id": 2,
"userUuid": "b1f8def8-aa1d-4a57-b743-174a6ee738ec",
"email": "jessika76#hotmail.com",
"nawisNumber": "NAWIS/2022/54682884"
},
"category": {
"id": 1,
"categoryUuid": "3a4def94-dd1a-451c-8f84-476096203710",
"name": "Front-End Development",
"slugUrl": "Front-End-Development-18-06-2022-ec0a7634-b710-4723-b646-4cde33d3d15a"
},
"duration": {
"id": 23,
"durationUuid": "3500b0d0-8d98-46d6-80d8-6363c09e887c",
"duration": "5 Months"
},
"enrollments": [],
"ratings": []
}
],
"meta": {
"totalItems": 209,
"itemCount": 3,
"itemsPerPage": 6,
"totalPages": 35,
"currentPage": 1
},
"links": {
"first": "http://ourakademy.com/api/v1/courses?limit=6",
"previous": "",
"next": "http://ourakademy.com/api/v1/courses?page=2&limit=6",
"last": "http://ourakademy.com/api/v1/courses?page=35&limit=6"
}
}
}
Assuming you put your json response in sampleJson variable
let sampleJson = YOUR JSON RESPONE
let sum = 0
let noOfRatings = 0
if(sampleJson && sampleJson.data && sampleJson.data.items){
sampleJson.data.items.forEach(item => {
item.ratings.forEach(i => {
if (i && i.rating) { sum += i.rating; noOfRatings++ }
})
});
if(sum && noOfRatings){
let averateRating = sum / noOfRatings
console.log('Average Rating : ',averateRating)
}
}
You will get average rating using this code.
Hope it helps :)
This is how i fixed the problem
const courses: any = await this.find();
for (let i = 0; i < courses.length; i++) {
const course = courses[i];
const sum: any = course.ratings.reduce((accumulator, object) => {
return accumulator + object.rating;
}, 0);
courses[i] = {
...course,
avg: sum / course.ratings.length,
};
}
return courses;

How to pull and display data from another source in Javascript

I am trying to wrap my head around this. I just started learning javascript. Basically on my site, I have a plugin/script that asks the user a bunch of questions and at the end, it asks for their email address. I am using emailjs to send the info (well that's what I am trying to do) but can't figure out the proper javascript code.
In the code, if I put my email address in the variable templateParams under to_name: The email gets sent when the user enters their email and I receive it but it's blank with no data. I don't know how to grab the data with the info below from the plugin documentation.
onSendEmail: function(emailData) {
// User clicked send button on share by email. You have to manage sending
// the email yourself with the following data received in the parameter:
console.log(emailData);
/*
{
"data": {
"cvData": [
{
"name": "overall",
"value": 71,
"feedback": "Excellent"
},
{
"name": "smoothness",
"value": 52,
"tip": "Smoothness can be affected by using correct products.",
"info": "Healthy skin is free of dryness, hyperpigmentation, ...",
"feedback": "Good"
},
{
"name": "radiance",
"value": 73,
"info": "Skin radiance is the glowy, vibrant look we ...",
"feedback": "Excellent"
},
...
],
"products": {
"morning": {
"highend": [{product1},{product2},{product3}],
"economy": [{product4}, {product5}, {product6}],
"standard": [{product7}, {product8}, {product9}]
},
"evening": {
"highend": [{product1},{product2},{product3}],
"economy": [{product4}, {product5}, {product6}],
"standard": [{product7}, {product8}, {product9}]
}
},
"activeRoutine": "evening",
"activePriceGroup": "standard",
"activeFilters": {
"skin_type": { "value": "normal" },
"gender_ui": { "value": "female" },
"age_ui": { "value": 31 },
"eyebags_ui": { "value": 1 },
"dull_tired_ui": { "value": 1 },
"redness_ui": { "value": 1 },
"lat": { "value": 39.47504 },
"lon": { "value": -0.4117344 },
"darkspots_ui": { "value": 1 },
"wrinkles_ui": { "value": 1 }
},
"activeSelections": {
"userAllowsCamera": true,
"locationData": {
"status": "done",
"location": {
"lat": 39.47504, "lon": -0.4117344,
"city": "Valencia", "country": "Spain", "area": "Valencia",
"uvIndex": 9, "pollution": 30, "humidity": 77
}
},
"skin_type": "normal",
"skin_concerns": ["dull_tired", "redness"],
"eyebags": 1,
"darkspots": 1,
"wrinkles": 1,
"gender": "female",
"age": "31",
"selfieSource": "video"
},
},
"email": "user#example.com",
"locale": "en",
"partnerId": "XXXXXXX",
...
}
*/
let templateParams = {
to_name: 'email',
from_name: 'abc',
message: 'random message'
};
emailjs.send('SERVICE_ID', 'TEMPLATE_ID', templateParams)
.then(function(response) {
console.log('SUCCESS!', response.status, response.text);
}, function(error) {
console.log('FAILED...', error);
});
},
};

How to add post fields on the basis of result of elastic search

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.

Iterate over JSON AJAX response [closed]

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;
})

Angular bootstrap modal toggle checked for data already present

Firstly i apologize for a lengthy question as i cant post a plunker because this has services which brings data from a backend. Hence i posted as much data as i can as samples.
I have an angular js app that uses bootstrap. I have a modal defined which has the following table:
<div class="panel panel-default" style="float:left;width:525px;">
<div class="panel-body" data-spy="scroll" data-target="#navbar-example" data-offset="0" style="height:200px;overflow:auto;position:relative;">
<table class="table table-hover checkbox">
<tr>
<th>Course</th>
<th>Title</th>
<th>Credits</th>
</tr>
<tr ng-repeat="child in requirements">
{% verbatim %}
<td class="vcenter">
<input type="checkbox" ng-checked="" ng-click="toggleCheck(child)" ng-disabled="required == (planned + completed) && (selectedCourses.indexOf(child) == -1)" value=""/>
{{child.course.subject}}-{{child.course.course_no}}
</td>
<td class="vcenter">{{child.course.course_name}}</td>
{% endverbatim %}
<td class="vcenter">3</td>
</tr>
</table>
</div>
This is how i defined its javascript:
var ModalInstanceCtrl = function (MpttService, PlannedService, RequirementsService, $scope, $http, $log, $modalInstance, mpttid, mpttrequired, mpttcompleted, mpttplanned) {
//debugger
$scope.subcategory = mpttid;
$scope.selectedCourses= [];
$scope.completed = mpttcompleted;
$scope.required = mpttrequired;
$scope.planned = mpttplanned;
MpttService.getMptt(function(data){
$scope.mpttdetails = data;
console.log(data);
});
PlannedService.getPlanned(function(data){
$scope.planneddetails = data;
console.log(data);
});
RequirementsService.getRequirements($scope.subcategory,function(data){
$scope.requirements = data;
console.log(data);
});
angular.forEach(mpttid.subcategory, function(item) {
$scope.selectedCourses.push(item.requirements);
});
$scope.getPercentage = function () {
return (($scope.planned+$scope.completed)/($scope.required)*100).toFixed(2);
}
$scope.toggleCheck = function (course) {
if (($scope.selectedCourses.indexOf(course) === -1)) {
$scope.selectedCourses.push(course);
$scope.planned += 3;
} else {
$scope.selectedCourses.splice($scope.selectedCourses.indexOf(course), 1);
$scope.planned -= 3;
}
$scope.getPercentage();
};
$scope.checkedfunction = function(course){
}
$scope.ok = function () {
//$scope.subcategory.subcategory2 = [];
for(var i = 0; i < $scope.selectedCourses.length; i++){
//$scope.subcategory.subcategory2.push({course: $scope.selectedCourses[i], term:"--",credit:"--",grade:"--"});
var variablesToSend = {
"student": 2773951,
"category": $scope.subcategory,
"course_name": ($scope.selectedCourses[i].course.subject).concat("-",$scope.selectedCourses[i].course.course_no),
"title": $scope.selectedCourses[i].course.title,
"credit": 3,
"term": 'none',
}
$http.post('/api/studentplannedcredit/', variablesToSend).then(function(response){
console.log(response);
//alert('post added');
document.location.reload(true);
}, function(response){
console.log(response);
alert('Unable to add Course');
});
}
$modalInstance.close();
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
};
In this app, when the modal opens, the user can check the courses he wants and save them using the save() function. Since there are limitations on the number of courses to be taken, the table will disable automatically when the required number of courses have been checked.
This is how my json looks like:
Planneddetails:
[
{
"student": 2773951,
"category": 163,
"course_name": "HIST-1301",
"title": "History of the United States I",
"credit": 3,
"term": "2014FA"
},
{
"student": 2773951,
"category": 169,
"course_name": "ANTH-2401",
"title": "Physical Anthropology",
"credit": 3,
"term": "2014SU"
},
{
"student": 2773951,
"category": 169,
"course_name": "ENVR-1402",
"title": "Environmental Science II",
"credit": 3,
"term": "2015SU"
},
{
"student": 2773951,
"category": 157,
"course_name": "HIST-1302",
"title": "History of the United States II",
"credit": 3,
"term": "none"
}
]
MpttDetails:
{
"student_program": {
"academic_program": {
"id": 596,
"program_title": "Associate in Sciences Degree",
"required_credits": 60
},
"id": 3685,
"student": 2773951,
"credits_completed": 26,
"academic_program_gpa": null,
"primary_program": true
},
"category": {
"id": 163,
"name": "CRITICAL READING AND WRITING",
"min_credit": 6,
"parent": {
"id": 162,
"name": "TIER 1 - CORE FOUNDATIONS",
"min_credit": 13,
"parent": {
"id": 149,
"academic_program": null,
"name": "AS.SCIENCE",
"min_credit": 60,
"max_credit": null,
"parent": 128,
"lft": 30,
"rght": 71,
"tree_id": 2,
"level": 1
},
"level": 2
},
"level": 3
},
"student_academic_credit": {
"accad_credit_id": 29328778,
"course": 81,
"student": 2773951,
"course_name": "ENGL-1301",
"title": "Composition I",
"credit": 3,
"final_grade": "C",
"term": "2012FA"
}
},
{
"student_program": {
"academic_program": {
"id": 596,
"program_title": "Associate in Sciences Degree",
"required_credits": 60
},
"id": 3685,
"student": 2773951,
"credits_completed": 26,
"academic_program_gpa": null,
"primary_program": true
},
"category": {
"id": 154,
"name": "CB050",
"min_credit": 3,
"parent": {
"id": 152,
"name": "HUMANITY, CREATIVITY AND THE AESTHETIC EXPERIENCE",
"min_credit": 6,
"parent": {
"id": 150,
"academic_program": null,
"name": "TIER 2 - CORE DOMAINS",
"min_credit": 26,
"max_credit": null,
"parent": 149,
"lft": 41,
"rght": 60,
"tree_id": 2,
"level": 2
},
"level": 3
},
"level": 4
},
"student_academic_credit": {
"accad_credit_id": 29328777,
"course": 209,
"student": 2773951,
"course_name": "ARTS-1301",
"title": "Art Apprec",
"credit": 3,
"final_grade": "A",
"term": "2012FA"
}
},
and my Requirements json:
[
{
"category": 163,
"course": {
"course_id": 1023,
"subject": "HIST",
"course_no": "1301",
"course_name": "History of the United States I",
"title": "History of the United States I",
"local_govt_code": "5401025125",
"academic_level": "CR",
"grade_scheme": "CR",
"credit_type": "I",
"course_type": "1",
"course_level": "1",
"min_credit": 3,
"max_credit": null,
"prereqs": 7,
"cip": "54.0102",
"ceus": "",
"transfer_status": "060"
}
},
{
"category": 163,
"course": {
"course_id": 81,
"subject": "ENGL",
"course_no": "1301",
"course_name": "Composition I",
"title": "Composition I",
"local_govt_code": "2313015112",
"academic_level": "CR",
"grade_scheme": "CR",
"credit_type": "I",
"course_type": "1",
"course_level": "1",
"min_credit": 3,
"max_credit": null,
"prereqs": 5,
"cip": "23.0401",
"ceus": "",
"transfer_status": "010"
}
}
]
The next step was to check all the courses in the table that have already been taken. These details will be retrieved from the mpttdetails and the planneddetails.
So how do i make the modal open with the table having courses already checked for those which are present in the mpttdetails and planned details?
Note: the courses in the $scope.requirements.course.{{subject}}-{{course_no}} needs to be compared with the mpttdetails.student_academic_credit.course_name and the planneddetails.course_name . But i am unable to figure out how to achieve this. Please help!

Categories

Resources