Related
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;
I am trying to get the result of the below array though no idea what am I missing here,
[
{
"Id": "10",
"FileName": "TechnicalBook_2021-08-26T12:36:48Z",
"Book": "ABC P1",
"Location": "USA",
"LastModified": "2021-08-26T12:36:48Z"
},
{
"Id": "11",
"FileName": "SocialBook_2021-08-26T12:36:48Z",
"Book": "XYZ P1",
"Location": "USA",
"LastModified": "2021-08-26T15:36:48Z"
},
{
"Id": "12",
"FileName": "TechnicalBook_2021-08-26T15:36:48Z",
"Book": "ABC P2",
"Location": "USA",
"LastModified": "2021-08-26T12:36:48Z"
},
{
"Id": "13",
"FileName": "SocialBook_2021-08-26T15:36:48Z",
"Book": "XYZ P2",
"Location": "USA",
"LastModified": "2021-08-26T15:36:48Z"
},
{
"Id": "14",
"FileName": "SocialBook_2021-08-26T17:36:48Z",
"Book": "XYZ P3",
"Location": "USA",
"LastModified": "2021-08-26T17:36:48Z"
}
]
And I am trying to obtain below output
[
{
"FileName": "TechnicalBook",
"TechnicalBook_Count": "2"
},
{
"FileName": "SocialBook",
"SocialBook_Count": "3"
}
]
Below code, I tried though not getting the proper output, any alternate suggestions here? Because 'FileName' will change every time, new DateTime will append in FileName.
var occurrences = { };
for (var i = 0, j = arr.length; i < j; i++) {
occurrences[arr[i]] = (occurrences[arr[i]] || 0) + 1;
}
You can do it like this:
var data =
[
{
"Id": "10",
"FileName": "TechnicalBook_2021-08-26T12:36:48Z",
"Book": "ABC P1",
"Location": "USA",
"LastModified": "2021-08-26T12:36:48Z"
},
{
"Id": "11",
"FileName": "SocialBook_2021-08-26T12:36:48Z",
"Book": "XYZ P1",
"Location": "USA",
"LastModified": "2021-08-26T15:36:48Z"
},
{
"Id": "12",
"FileName": "TechnicalBook_2021-08-26T15:36:48Z",
"Book": "ABC P2",
"Location": "USA",
"LastModified": "2021-08-26T12:36:48Z"
},
{
"Id": "13",
"FileName": "SocialBook_2021-08-26T15:36:48Z",
"Book": "XYZ P2",
"Location": "USA",
"LastModified": "2021-08-26T15:36:48Z"
},
{
"Id": "14",
"FileName": "SocialBook_2021-08-26T17:36:48Z",
"Book": "XYZ P3",
"Location": "USA",
"LastModified": "2021-08-26T17:36:48Z"
}
]
var prefixesAll = data.map(a => a.FileName.split('_')[0]);
var prefixesUnique = [...new Set(prefixesAll)];
var prefixCounts = prefixesUnique.map(a => ({
"FileName": a,
"Count": data.filter(b => b.FileName.startsWith(a)).length
}));
console.log(prefixesAll);
console.log(prefixesUnique);
console.log(prefixCounts);
In an array of objects you should always aim for each object to have the same keys, so I've done that here.
That code will output all of the prefixes, then a unique list of the prefixes, then the count of each prefix:
[
"TechnicalBook",
"SocialBook",
"TechnicalBook",
"SocialBook",
"SocialBook"
]
[
"TechnicalBook",
"SocialBook"
]
[
{
"FileName": "TechnicalBook",
"Count": 2
},
{
"FileName": "SocialBook",
"Count": 3
}
]
What you're doing here is not so much counting occurrences but transforming data from one format into another. However, you only need to take a couple of steps to convert your data into another format. See comments below...
// your data
var dataArr = [
{
"Id": "10",
"FileName": "TechnicalBook_2021-08-26T12:36:48Z",
"Book": "ABC P1",
"Location": "USA",
"LastModified": "2021-08-26T12:36:48Z"
},
{
"Id": "11",
"FileName": "SocialBook_2021-08-26T12:36:48Z",
"Book": "XYZ P1",
"Location": "USA",
"LastModified": "2021-08-26T15:36:48Z"
},
{
"Id": "12",
"FileName": "TechnicalBook_2021-08-26T15:36:48Z",
"Book": "ABC P2",
"Location": "USA",
"LastModified": "2021-08-26T12:36:48Z"
},
{
"Id": "13",
"FileName": "SocialBook_2021-08-26T15:36:48Z",
"Book": "XYZ P2",
"Location": "USA",
"LastModified": "2021-08-26T15:36:48Z"
},
{
"Id": "14",
"FileName": "SocialBook_2021-08-26T17:36:48Z",
"Book": "XYZ P3",
"Location": "USA",
"LastModified": "2021-08-26T17:36:48Z"
}
];
// create storage object
var fileObject = {};
// loop through data
dataArr.forEach(d => {
// get the fileName (remove date)
let fileName = d.FileName.split("_")[0];
// check if fileObject has a fileName property
// if not add it and set it to 0
fileObject[fileName] = fileObject[fileName] || 0,
// then/else increment the count
fileObject[fileName] += 1
}),
This will give you:
console.log("fileObject:", fileObject)
//=> fileObject: { TechnicalBook: 2, SocialBook: 3 }
Now that you've done the counting then it's simply a matter of reformatting:
// create output array
var bookArr = [];
// loop through fileObject
Object.keys(fileObject).forEach(key => {
// create a temporary object
let obj = {
FileName: key
};
// add the count to obj
obj[`${key}_Count`] = fileObject[key],
// add obj to the array
bookArr.push(obj)
})
This will give you:
console.log("bookArr:", bookArr)
/*=> bookArr: [ { FileName: 'TechnicalBook', TechnicalBook_Count: 2 },
{ FileName: 'SocialBook', SocialBook_Count: 3 } ]
*/
And as you seem to want the output in JSON format then:
var bookJSON = JSON.stringify(bookArr, null, 4);
console.log(bookJSON)
/*
[
{
"FileName": "TechnicalBook",
"TechnicalBook_Count": 2
},
{
"FileName": "SocialBook",
"SocialBook_Count": 3
}
]
*/
Hoped that helped. :)
I have a json array data in this format:
{
"jobs": [
{
"id": "some_random_id_1",
"email": "some#email.com",
"email_type": "html",
"status": "pending",
"job_fields": {
"TITLE": "job title here"
},
"stats": {
"applied": 40,
"rejected": 20
}
},
{
"id": "some_random_id_2",
"email": "some#email.com",
"email_type": "html",
"status": "pending",
"job_fields": {
"TITLE": "job title here"
},
"stats": {
"applied": 30,
"rejected": 20
}
},
{
"id": "some_random_id_3",
"email": "some#email.com",
"email_type": "html",
"status": "pending",
"job_fields": {
"TITLE": "job title here"
},
"stats": {
"applied": 13,
"rejected": 1
}
},
{
"id": "some_random_id_4",
"email": "some#email.com",
"email_type": "html",
"status": "pending",
"job_fields": {
"TITLE": "job title here"
},
"stats": {
"applied": 13,
"rejected": 1
}
}
],
"job_id": "some_id",
"total_jobs": 60
}
where I just need to access the jobs object and grab id and status and all info for job_fields and stats (or all info for now).
// example is from here
// https://pivottable.js.org/examples/mps.html
$(function(){
$.getJSON("data.json", function(mps) {
$("#output").pivotUI(mps);
});
});
the example works with this json format:
[{
"Province": "Quebec",
"Party": "NDP",
"Age": 22,
"Name": "Liu, Laurin",
"Gender": "Female"
},
{
"Province": "Quebec",
"Party": "Bloc Quebecois",
"Age": 43,
"Name": "Mourani, Maria",
"Gender": "Female"
},
{
"Province": "Ontario",
"Party": "Conservative",
"Age": "",
"Name": "O'Toole, Erin",
"Gender": "Male"
}
]
I am not sure how to modify the javascript so it can read my json format. I can't modify the json format to match the above format, so in the above javascript example, province, party, etc are all passed to the function.
I want to do the same but with my json format, so output id, status, all members of job_fields (ex: TITLE, etc. ), all members of stats (ex: applied, rejected.
Assuming all jobs have job_fields.TITLE, stats.applied and stats.rejected maybe the following will do:
const json = {
"jobs": [
{
"id": "some_random_id_1",
"email": "some#email.com",
"email_type": "html",
"status": "pending",
"job_fields": {
"TITLE": "job title here"
},
"stats": {
"applied": 40,
"rejected": 20
}
},
{
"id": "some_random_id_2",
"email": "some#email.com",
"email_type": "html",
"status": "pending",
"job_fields": {
"TITLE": "job title here"
},
"stats": {
"applied": 30,
"rejected": 20
}
},
{
"id": "some_random_id_3",
"email": "some#email.com",
"email_type": "html",
"status": "pending",
"job_fields": {
"TITLE": "job title here"
},
"stats": {
"applied": 13,
"rejected": 1
}
},
{
"id": "some_random_id_4",
"email": "some#email.com",
"email_type": "html",
"status": "pending",
"job_fields": {
"TITLE": "job title here"
},
"stats": {
"applied": 13,
"rejected": 1
}
}
],
"job_id": "some_id",
"total_jobs": 60
};
console.log(
json.jobs.map(
(job)=>({
id:job.id,
status:job.status,
title:job.job_fields.TITLE,
applied:job.stats.applied,
rejected:job.stats.rejected
})
)
);
You can use map and use Object.assign and spread operator to make an object
var obj={"jobs":[{"id":"some_random_id_1","email":"some#email.com","email_type":"html","status":"pending","job_fields":{"TITLE":"job title here"},"stats":{"applied":40,"rejected":20}},{"id":"some_random_id_2","email":"some#email.com","email_type":"html","status":"pending","job_fields":{"TITLE":"job title here"},"stats":{"applied":30,"rejected":20}},{"id":"some_random_id_3","email":"some#email.com","email_type":"html","status":"pending","job_fields":{"TITLE":"job title here"},"stats":{"applied":13,"rejected":1}},{"id":"some_random_id_4","email":"some#email.com","email_type":"html","status":"pending","job_fields":{"TITLE":"job title here"},"stats":{"applied":13,"rejected":1}}],"job_id":"some_id","total_jobs":60}
var result = obj.jobs.map(({id,status,job_fields,stats}) => {
return Object.assign({}, {id}, {status}, {...job_fields}, {...stats});
});
console.log(result);
Or you can make it shorter like:
var result = obj.jobs.map( ({id,status,job_fields,stats}) => Object.assign({},{id},{status},{...job_fields},{...stats}) );
Can try with below snippet:
$(function(){
$.getJSON("data.json", function(orgData) {
var pivotData = [];
orgData.jobs.forEach(function (job, ind) {
var reqInfo = {};
reqInfo['id'] = job.id;
reqInfo['status'] = job.status;
reqInfo['jobTitle'] = job.job_fields && job.job_fields.TITLE;
reqInfo['applied'] = job.stats && job.stats.applied;
reqInfo['rejected'] = job.stats && job.stats.rejected;
pivotData.push(reqInfo)
})
$("#output").pivotUI(pivotData);
});
});
$("#output").pivotUI(mps.jobs);
I want to remove object based on conditional check from the JSON object using angularjs/jQuery.
I tried with below code but output is not as expected.
Demo: https://plnkr.co/edit/EWwbETITqn7G79Xypt0g?p=preview
angular.module('ui.bootstrap.demo').controller('DataCtrl', function ($scope) {
$scope.responseData = {
"data": [{
"name": "Machine", "quantity": 20, "snVal": 22,
"machine1": [{ "id": 2009, "machineName": "ASD1", "trackID": "34219", "status": "delivered" },
{ "id": 27893, "machineName": "PX20AA", "trackID": "3422", "status": "avail" }],
"machine2": [{ "id": 1023, "machineName": "XY22", "trackID": "1345", "status": "avail" },
{ "id": 1233, "machineName": "PP3DF", "trackID": "112", "status": "delivered" }
]
}]
}
console.log("R1 :: " + JSON.stringify($scope.responseData));
$scope.newResponse = $.grep($scope.responseData.data, function (element, index) { return element.status == "delivered" }, true);
console.log("R2 after removing elements:: " + JSON.stringify($scope.newResponse));
});
Try this,
let responseData = { "data": [{ "name": "Machine", "quantity": 20, "snVal": 22, "machine1": [{ "id": 2009, "machineName": "ASD1", "trackID": "34219", "status": "delivered" }, { "id": 27893, "machineName": "PX20AA", "trackID": "3422", "status": "avail" }], "machine2": [{ "id": 1023, "machineName": "XY22", "trackID": "1345", "status": "avail" }, { "id": 1233, "machineName": "PP3DF", "trackID": "112", "status": "delivered" }] }] } ;
let newResponse = responseData;
newResponse.data.forEach(function (item) {
for (j in item) {
if (j.includes("machine")) {
//better you check if type is array, using Object.prototype.toString.call(j) === "[object Array]"
item[j] = item[j].reduce(function (acc, machine) {
if (machine.status !== "delivered"){
acc.push(machine);
}
return acc;
}, []);
}
}
})|
console.log(newResponse);
Here we are just iterating through all objects in the data field. Since properties like machine1, machine2 is an array, we iterate through it and filter all machines which are not delivered.
You must note that I have used a for-in loop and array reduce() method here.
I have the below JSON response. In Backbone I want to filter some objects(names) from the array
For example - Here i need to loop only 'Jack','Mcd' objects(names. Need to get only Jack and Mcd names from arrary.
Can anyone give me any ideas to implement?
resultstest = {
"r": [{
"IsActive": false,
"re": {
"Name": "Depo"
},
"Expire": "Oct8, 2013",
"Clg": [{
"Name": "james",
"Rate": 0.05
}, {
"Name": "Jack",
"Rate": 0.55
}, {
"Name": "Ander",
"Rate": 0.46
}, {
"Name": "Mcd",
"Rate": 0.01,
}],
},
{
"IsActive": false,
"re": {
"Name": "Depo"
},
"Expire": "Oct8, 2013",
"Clg": [{
"Name": "james",
"Rate": 0.05
}, {
"Name": "Jack",
"Rate": 0.55
}, {
"Name": "Mcd",
"Rate": 0.01,
}],
},
{
"IsActive": false,
"re": {
"Name": "Depo"
},
"Expire": "Oct8, 2013",
"Clg": [{
"Name": "james",
"Rate": 0.05
}, {
"Name": "Jack",
"Rate": 0.55
}, {
"Name": "Mcd",
"Rate": 0.01,
}],
}]
};
loadjson = function (input) {
if (_.isArray(input)) {
var collection = new CompeCollection();
_.each(input, function (modelData) {
....
});
return collection;
}
};
var tablesResult = loadjson(resultstest.r[0].Clg); // can we filter here like resultstest.r[0].Clg(!="james" && !="Ander")
Is there any array method to filter those objects while passing to loadjson function? Any help would be helpful.
Thanks
You can use Array.filter method of arrays supported in modern browsers. For compatibility of old browsers, you can use _.filter (http://underscorejs.org/#filter).
So your code would be like,
var tablesResult = loadjson(_.filter(resultstest.r[0].Clg, function(clg) { return (clg.name !="james" && clg.name !="Ander"); }))
To DRY your code, you can event create this filter function separately and simple reference it here. Like,
var collegeFilter = function(clg) { return (clg.name !="james" && clg.name !="Ander"); }
...
var tablesResult = loadjson(_.filter(resultstest.r[0].Clg, collegeFilter));