Angular bootstrap modal toggle checked for data already present - javascript

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!

Related

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

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.

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 get the respective JSON object based on id

how to get the respective nested JSON object based on Id. For example below is my complete JSON.
[
{
"id": 1,
"title": "ASD Headquarters",
"items": [
{
"id": 11,
"title": "San Jose",
"items": [
{
"id": 13,
"title": "Jensen Chapman's Team",
"items": [
{
"id": 14,
"title": "Jimmy John"
},
{
"id": 15,
"title": "Daniel Mills"
},
{
"id": 16,
"title": "Chris Boden"
}
]
}
]
},
{
"id": 12,
"title": "Irvine",
"items": [
{
"id": 23,
"title": "Tracey Chapman's Team",
"items": [
{
"id": 24,
"title": "San Jesus"
},
{
"id": 25,
"title": "Fat Albert"
},
{
"id": 26,
"title": "Connor McDavid"
}
]
}
]
},
{
"id": 30,
"title": "San Diego",
"items": [
{
"id": 31,
"title": "Duran Duran's Team",
"items": [
{
"id": 32,
"title": "Amberlynn Pinkerton"
},
{
"id": 33,
"title": "Tony Mejia"
},
{
"id": 34,
"title": "Richard Partridge"
},
{
"id": 35,
"title": "Elliot Stabler"
}
]
},
{
"id": 40,
"title": "Steely Dan's Team",
"items": [
{
"id": 36,
"title": "Tony Stark"
},
{
"id": 37,
"title": "Totally Rad"
},
{
"id": 38,
"title": "Matt Murdock"
},
{
"id": 39,
"title": "Stan Lee"
}
]
}
]
}
]
}
]
From the above json how do i filter only particular nested object which have id as 11 => {"id": 11} using underscore.js
Output which i required is : {
"id":11,
"title":"San Jose",
"items":[
{
"id":13,
"title":"Jensen Chapman's Team",
"items":[
{
"id":14,
"title":"Jimmy John"
},
{
"id":15,
"title":"Daniel Mills"
},
{
"id":16,
"title":"Chris Boden"
}
]
}
]
}
You can use a recursive algorithm to look for an object in the current array as well as the nested ones.
var data = [{"id":1,"title":"ASD Headquarters","items":[{"id":11,"title":"San Jose","items":[{"id":13,"title":"Jensen Chapman's Team","items":[{"id":14,"title":"Jimmy John"},{"id":15,"title":"Daniel Mills"},{"id":16,"title":"Chris Boden"}]}]},{"id":12,"title":"Irvine","items":[{"id":23,"title":"Tracey Chapman's Team","items":[{"id":24,"title":"San Jesus"},{"id":25,"title":"Fat Albert"},{"id":26,"title":"Connor McDavid"}]}]},{"id":30,"title":"San Diego","items":[{"id":31,"title":"Duran Duran's Team","items":[{"id":32,"title":"Amberlynn Pinkerton"},{"id":33,"title":"Tony Mejia"},{"id":34,"title":"Richard Partridge"},{"id":35,"title":"Elliot Stabler"}]},{"id":40,"title":"Steely Dan's Team","items":[{"id":36,"title":"Tony Stark"},{"id":37,"title":"Totally Rad"},{"id":38,"title":"Matt Murdock"},{"id":39,"title":"Stan Lee"}]}]}]}];
console.log(find(12, data));
function find(id, [head, ...tail]) {
if (!head)
return null;
return checkObj(id, head) || find(id, tail);
}
function checkObj(id, obj) {
return obj.id === id ? obj : find(id, obj.items || [])
}
This also uses parameter destructuring in order to conveniently separate the "head" of the array from its "tail".
It could also be done within a single function.
var data = [{"id":1,"title":"ASD Headquarters","items":[{"id":11,"title":"San Jose","items":[{"id":13,"title":"Jensen Chapman's Team","items":[{"id":14,"title":"Jimmy John"},{"id":15,"title":"Daniel Mills"},{"id":16,"title":"Chris Boden"}]}]},{"id":12,"title":"Irvine","items":[{"id":23,"title":"Tracey Chapman's Team","items":[{"id":24,"title":"San Jesus"},{"id":25,"title":"Fat Albert"},{"id":26,"title":"Connor McDavid"}]}]},{"id":30,"title":"San Diego","items":[{"id":31,"title":"Duran Duran's Team","items":[{"id":32,"title":"Amberlynn Pinkerton"},{"id":33,"title":"Tony Mejia"},{"id":34,"title":"Richard Partridge"},{"id":35,"title":"Elliot Stabler"}]},{"id":40,"title":"Steely Dan's Team","items":[{"id":36,"title":"Tony Stark"},{"id":37,"title":"Totally Rad"},{"id":38,"title":"Matt Murdock"},{"id":39,"title":"Stan Lee"}]}]}]}];
console.log(find(12, data));
function find(id, [head, ...tail]) {
if (!head)
return null;
if (head.id === id)
return head;
return find(id, head.items || []) || find(id, tail);
}

Using map to access nested json in react native

I am trying to access keys and arrays in my json structure with Array.map() but I'm missing something.
Here's my JSON:
{
"payload": [
{
"id": 1,
"name": "Atta",
"brands": [
{
"id": 118,
"name": "Wheatola",
"subProducts": [
{
"id": 858,
"name": "Chakki Aata",
"minPrice": 52,
"maxPrice": 56
},
{
"id": 2,
"name": "Chakki Atta",
"minPrice": 222,
"maxPrice": 236
}
]
}
]
},
{
"id": 16,
"name": "Rice (Branded)",
"brands": [
{
"id": 25,
"name": "CookStar",
"subProducts": [
{
"id": 1163,
"name": "Best Basmati",
"creditDays": 0,
"minPrice": 5600,
"maxPrice": 5600
},
{
"id": 863,
"name": "Extra Long Grain Basmati",
"creditDays": 0,
"minPrice": 7800,
"maxPrice": 7800
}
]
}
]
}
]
}
I want to access payload.name, payload.brands.name(s), payloads.brands.subproducts.name(s) with Array.map() and render the values in components. How do I access nested json like using map()?
Expected output is:
Atta, Wheatola, Chakki Aata
Atta, Wheatola, Chakki Aata
Rice (Branded), Cookstar, Best Basmati
Rice (Branded), Cookstar, Extra Long Grain Basmati
You need to nest Array.map()
var data = {
"payload": [
{
"id": 1,
"name": "Atta",
"brands": [
{
"id": 118,
"name": "Wheatola",
"subProducts": [
{
"id": 858,
"name": "Chakki Aata",
"minPrice": 52,
"maxPrice": 56
},
{
"id": 2,
"name": "Chakki Atta",
"minPrice": 222,
"maxPrice": 236
}
]
}
]
},
{
"id": 16,
"name": "Rice (Branded)",
"brands": [
{
"id": 25,
"name": "CookStar",
"subProducts": [
{
"id": 1163,
"name": "Best Basmati",
"creditDays": 0,
"minPrice": 5600,
"maxPrice": 5600
},
{
"id": 863,
"name": "Extra Long Grain Basmati",
"creditDays": 0,
"minPrice": 7800,
"maxPrice": 7800
}
]
}
]
}
]
}
const renderData = data.payload.map((payload) => {
return payload.brands.map(brand =>{
return brand.subProducts.map(subProduct => {
return `${payload.name}, ${brand.name}, ${subProduct.name}`
}).join("\n")
}).join("\n")
}).join("\n")
console.log(renderData);
Here might be a working example (without styling or anything):
render() {
return (
<div>
{
json.payload.map(j =>
<div>
{j.name}
{j.brands.map(b =>
<div>
{b.name}
{b.subProducts.map(s =>
<div>
{s.name}
</div>)
}
</div>
)}
</div>
)
}
</div>
);
}
You probably need to style it, or combine it with a table and columns, because it just renders the values now.
You can also use forEach since you'll have to nest map calls but you expect a flat array (?) in the end :
var json = {
"payload": [{
"id": 1,
"name": "Atta",
"brands": [{
"id": 118,
"name": "Wheatola",
"subProducts": [{
"id": 858,
"name": "Chakki Aata",
"minPrice": 52,
"maxPrice": 56
},
{
"id": 2,
"name": "Chakki Atta",
"minPrice": 222,
"maxPrice": 236
}
]
}]
},
{
"id": 16,
"name": "Rice (Branded)",
"brands": [{
"id": 25,
"name": "CookStar",
"subProducts": [{
"id": 1163,
"name": "Best Basmati",
"creditDays": 0,
"minPrice": 5600,
"maxPrice": 5600
},
{
"id": 863,
"name": "Extra Long Grain Basmati",
"creditDays": 0,
"minPrice": 7800,
"maxPrice": 7800
}
]
}]
}
]
}
var result = [];
json.payload.forEach(product => {
product.brands.forEach(brand => {
brand.subProducts.forEach(subProduct => {
result.push([product.name, brand.name, subProduct.name].join(', '));
});
});
});
console.log(result);

Ionic 2 (Angular) GroupBy Pipe

I'm having a trouble grouping my objects, I'm trying to use the ngx-group-by pipe but it doesn't seem to solve my problem.
Assuming the data structure is :
Every company has it products (which contains sub products), and it prices;
For example our company is XXX and it sales cars and motorcycles:
Products : TwoWheels , FourWheels
SubProducts : Bike,Motorcycle (TwoWheels) , Cars (FourWheels)
I'm trying to display the price for every SubProduct and group it by the ProductId
Here's my Json:
{
"id": 1,
"firstName": "test",
"lastName": "tast",
"displayName": "myname",
"profilePic": "none",
"location": "mylocation",
"pricingList": [
{
"id": 1,
"userId": 1,
"ProductId": 1,
"subProductId": 1,
"price": 50,
"subProduct": {
"id": 1,
"ProductId": 1,
"name": "MotorCycle",
"treatment": {
"id": 1,
"name": "TwoWheels"
}
},
"Product": {
"id": 1,
"name": "TwoWheels"
}
},
{
"id": 2,
"userId": 1,
"ProductId": 1,
"subTreatmentId": 7,
"price": 50,
"subProduct": {
"id": 7,
"ProductId": 1,
"name": "bike",
"Product": {
"id": 1,
"name": "TwoWheels"
}
},
"Product": {
"id": 1,
"name": "TwoWheels"
}
},
{
"id": 3,
"userId": 1,
"ProductId": 2,
"subTreatmentId": 8,
"price": 30,
"subProduct": {
"id": 8,
"treatmentId": 2,
"name": "Car",
"Product": {
"id": 2,
"name": "FourWheels"
}
},
"Product": {
"id": 2,
"name": "FourWheels"
}
}
]
}
And here's my Ionic 2/Angular html:
<div *ngFor="let p of User.pricingList | groupBy:p.ProductId">
<div class="ProductTitle">{{p.Product.name}}</div>
<div>
<div class="myClass">Name</div>
<div class="myClass">Price</div>
</div>
<div style="myClass2">
<div class="myClass">{{p.subProduct.name}}</div>
<div class="myClass">{{p.price}}</div>
</div>
</div>
GroupByPipe implementation

Categories

Resources