mongoDB - How do master-detail structure grouped detail collection specific fields summary - javascript

In a mongodb database with a master-detail structure, how do I ensure that the data in the detail table is grouped according to the status area while querying the master table. For example ...
Master, Row, Job, Fields, [Detail Status Grouped Count / Summary Object]
Edited:
sms_jobs collection example data is :
// 1
{
"_id": NumberInt("1"),
"company": {
"id": NumberInt("1"),
"name": "",
"sms_gateway_id": NumberInt("1"),
"sms_gateway_parameters": {
"password": "",
"username": ""
},
"is_active": true
},
"source_type": "form",
"source": {
"id": NumberInt("2"),
"company_id": NumberInt("1"),
"title": "Import Data Demo",
"description": "<p>Üst Açıklama</p>",
"footer_description": "<p>Alt Açıklama</p>",
"thanks_message": "Katiliminiz icin tesekkur ederiz.",
"sms_message": "{company} KVKK Aydinlatma Metni ve Acik Riza Onayi icin Dogrulama Kodunuz : {code} ( {form_link} )",
"digest": null,
"ts_digest": null,
"is_active": true,
"is_locked": false
},
"description": "Import Data Demo",
"status": "waiting",
"job_count": NumberInt("22145"),
"updated_at": ISODate("2020-08-15T17:00:49.252Z"),
"created_at": ISODate("2020-08-15T16:59:10.899Z")
}
sms_job_details collection example data is :
// 1
{
"_id": NumberInt("221462"),
"sms_job_id": NumberInt("1"),
"gsm": "",
"schedule_at": ISODate("2020-08-15T19:41:44.827Z"),
"raw_message": "{name} {surname} {id_number} {form_link} {reject_link}",
"message": "",
"status": "waiting", // I want this statuses grouped count my master table rows in line object
"expire_at": "2020-08-18T17:40:44.967Z",
"updated_at": ISODate("2020-08-15T18:45:53.727Z"),
"created_at": ISODate("2020-08-15T18:45:53.727Z")
}
// 2
{
"_id": NumberInt("221463"),
"sms_job_id": NumberInt("1"),
"gsm": "",
"schedule_at": ISODate("2020-08-15T19:41:44.827Z"),
"raw_message": "{name} {surname} {id_number} {form_link} {reject_link}",
"message": "",
"status": "failed", // I want this statuses grouped count my master table rows in line object
"expire_at": "2020-08-18T17:40:44.967Z",
"updated_at": ISODate("2020-08-15T18:45:53.727Z"),
"created_at": ISODate("2020-08-15T18:45:53.727Z")
}
// 3
{
"_id": NumberInt("221464"),
"sms_job_id": NumberInt("1"),
"gsm": "",
"schedule_at": ISODate("2020-08-15T19:41:44.827Z"),
"raw_message": "{name} {surname} {id_number} {form_link} {reject_link}",
"message": "",
"status": "success", // I want this statuses grouped count my master table rows in line object
"expire_at": "2020-08-18T17:40:44.967Z",
"updated_at": ISODate("2020-08-15T18:45:53.727Z"),
"created_at": ISODate("2020-08-15T18:45:53.727Z")
}
I experimented for approximately 4-5 hours. I could get the closest result with the following query.
db.getCollection("sms_jobs").aggregate([{
$lookup: {
from: "sms_job_details",
localField: "_id",
foreignField: "sms_job_id",
as: "data"
}
}, {
$unwind: "$data"
}, {
$group: {
_id: {
id: "$_id",
status: "$data.status"
},
qty: {
$sum: 1
}
}
}, {
$project: {
_id: "$_id.id",
qty: 1,
status: "$_id.status"
}
}])
And get this result :
// 1
{
"qty": 22145,
"_id": NumberInt("4"),
"status": "success"
}
// 2
{
"qty": 1,
"_id": NumberInt("3"),
"status": "success"
}
// 3
{
"qty": 22142,
"_id": NumberInt("1"),
"status": "success"
}
// 4
{
"qty": 1,
"_id": NumberInt("1"),
"status": "failed"
}
// 5
{
"qty": 2,
"_id": NumberInt("1"),
"status": "waiting"
}
// 6
{
"qty": 1,
"_id": NumberInt("3"),
"status": "failed"
}
// 7
{
"qty": 3,
"_id": NumberInt("3"),
"status": "waiting"
}
What do I want ?
The query result I want is as follows.
// 1
{
"_id": NumberInt("1"),
"company": {
"id": NumberInt("1"),
"name": "",
"sms_gateway_id": NumberInt("1"),
"sms_gateway_parameters": {
"password": "",
"username": ""
},
"is_active": true
},
"source_type": "form",
"source": {
"id": NumberInt("2"),
"company_id": NumberInt("1"),
"title": "Import Data Demo",
"description": "<p>Üst Açıklama</p>",
"footer_description": "<p>Alt Açıklama</p>",
"thanks_message": "Katiliminiz icin tesekkur ederiz.",
"sms_message": "{company} KVKK Aydinlatma Metni ve Acik Riza Onayi icin Dogrulama Kodunuz : {code} ( {form_link} )",
"digest": null,
"ts_digest": null,
"is_active": true,
"is_locked": false
},
"description": "Import Data Demo",
"status": "waiting",
"job_count": NumberInt("22145"),
"updated_at": ISODate("2020-08-15T17:00:49.252Z"),
"created_at": ISODate("2020-08-15T16:59:10.899Z"),
// Added part...
"status_countes": {
"success": NumberInt("20"),
"failed": NumberInt("2"),
"waiting": NumberInt("11"),
"canceled": NumberInt("0"),
"total": NumberInt("33")
},
}
Thank you in advance for your help...

Related

Partition messages by date, last read in angular

I want to partition my messages by date for my chat application(Similar to the Microsoft teams app)
The message data will be like
[
{
"id": 577,
"source": {
"userID": 56469,
"profilePictureUrl": "",
"name": "John J"
},
"body": "test test",
"readStatus": true,
"attachments": null,
"createdDateTime": "2022-09-20T07:59:28.873+00:00"
},
{
"id": 578,
"source": {
"userID": 56469,
"profilePictureUrl": "",
"name": "Don V"
},
"body": "ok",
"readStatus": true,
"attachments": null,
"createdDateTime": "2022-09-20T08:02:26.262+00:00"
},
{
"id": 628,
"source": {
"userID": 56470,
"profilePictureUrl": "",
"name": "Sam GP"
},
"body": "Hola",
"readStatus": true,
"attachments": null,
"createdDateTime": "2022-09-20T17:27:48.038+00:00"
},
{
"id": 629,
"source": {
"userID": 56470,
"profilePictureUrl": "",
"name": "Rawn OP"
},
"body": "ek",
"readStatus": true,
"attachments": null,
"createdDateTime": "2022-09-20T17:29:36.705+00:00"
},
{
"id": 630,
"source": {
"userID": 56470,
"profilePictureUrl": "",
"name": "Paul John"
},
"body": "hi",
"readStatus": true,
"attachments": null,
"createdDateTime": "2022-09-20T17:30:36.695+00:00"
},
{
"id": 631,
"source": {
"userID": 56470,
"profilePictureUrl": "",
"name": "Dennise V"
},
"body": "knock knock",
"readStatus": true,
"attachments": null,
"createdDateTime": "2022-09-20T17:32:38.035+00:00"
},
{
"id": 632,
"source": {
"userID": 56469,
"profilePictureUrl": "",
"name": "Shawn"
},
"body": "who's this",
"readStatus": true,
"attachments": null,
"createdDateTime": "2022-09-20T17:37:25.985+00:00"
},
{
"id": 633,
"source": {
"userID": 56469,
"profilePictureUrl": "",
"name": "Pater B"
},
"body": "I see",
"readStatus": true,
"attachments": null,
"createdDateTime": "2022-09-20T17:37:30.783+00:00"
},
{
"id": 634,
"source": {
"userID": 56469,
"profilePictureUrl": "",
"name": "Cera LO"
},
"body": "Will call you later",
"readStatus": true,
"attachments": null,
"createdDateTime": "2022-09-20T17:37:38.268+00:00"
},
{
"id": 642,
"source": {
"userID": 56469,
"profilePictureUrl": "",
"name": "Rose BH"
},
"body": "hello???????",
"readStatus": true,
"attachments": null,
"createdDateTime": "2022-09-21T05:25:56.642+00:00"
}
]
I need to arrange these data to show the messages by date like
------------------------------Sep 30-----------------------------
Messages sent/received on sep 30
------------------------------Yesterday--------------------------
Messages sent/received on yesterday
------------------------------Last read-------------------------
------------------------------Oct30-----------------------------
------------------------------Yesterday-------------------------
------------------------------Today-----------------------------
For displaying "Sep 30", "yesterday", and "Today" I've created a pipe that converts the timestamp into the month and "yesterday", "today" etc.
I already got the solution to arrange the message by date. But I have to arrange it under the "Last read" block too. Same as by dates. the flag "readStatus" is sed to check whether the message has been read or not" If it is false is should come under "Last read".
Any ideas? Any help will be appreciated.
I imagine you can has something like (if your data is in a variable "data"
dataOrder = {
readed: this.group(this.data.filter((x) => x.readStatus)),
notReaded: this.group(this.data.filter((x) => !x.readStatus)),
};
group(data: any[]) {
return data.reduce((a, b) => {
const dateTime=new Date(b.createdDateTime.substr(0,10)+"T00:00:00.00+00:00")
.getTime()
const element = a.find((x) => x.dateTime == dateTime);
if (!element) a.push({ dateTime:dateTime,data: [b] });
else element.data.push(b);
return a;
}, []);
}
See that "dataOrder" has two properties "readed" and "notReaded", each one are arrays of objects in the way
{
dateTime:a dateTime,
data:an array with the messages
}
This makes easy indicate the date using Angular date pipe, and loop over the messages
So, an .html like
<h1>Readed</h1>
<ng-container
*ngTemplateOutlet="messagedata; context: { $implicit: dataOrder.readed }"
></ng-container>
<h1>Not Readed</h1>
<ng-container
*ngTemplateOutlet="messagedata; context: { $implicit: dataOrder.notReaded }"
></ng-container>
<ng-template #messagedata let-data>
<div *ngFor="let readed of data">
{{ readed.dateTime | date }}
<div *ngFor="let message of readed.data">
{{ message.createdDateTime }} - {{ message.body }}
</div>
</div>
</ng-template>
I use the same template for both type of messages
A stackblitz
Update As the dataOrder it's only change at fisrt is better use a function
getDataOrdered(data:any[])
{
return {
readed: this.group(data.filter((x) => x.readStatus)),
notReaded: this.group(data.filter((x) => !x.readStatus)),
};
}
Then, we can, each time some message change its "readStatus" we can do
this.dataOrder=this.getDataOrdered(this.data)

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;

Parse json array and loop through all the data for Pivot.js

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

Need help in lodash combinations to get the below object

Below is my object First step is to check the socialAuth array of objects and get the platformName which has the showStats value as false.
I have accomplished the step1 as below
var arrList2 = _.pluck(_.where(creatorObj.socialAuth, {'showStats': false}), "platformName");
['Twitter'] is the output of the arrList2
var creatorObj =
{
"_id": "55e5b32f3874c964cc3dfe2e",
"firstName": "xyz",
"lastName": "abc",
"socialStats": [
{
"reach": 205976,
"_id": "asdfasdfasdf",
"profileUrl": null,
"engagements": 126,
"platformName": "Twitter"
}
],
"socialAuth": [
{
"screenName": "abc",
"userId": "12341234",
"_id": "55e5b3573874c964cc3dfe33",
"showStats": false,
"platformName": "Twitter"
},
{
"channelTitle": "xyz",
"channelId": "sdfgsdfgsdfg",
"_id": "55e5a040991c1321a5b9bd79",
"showStats": true,
"platformName": "Youtube"
}
]
};
Second step is to check the above arrList2 with the sociaStats array and remove the value from it and print the object again.
I need help in this second step.
I need the resulting object as
var creatorObj =
{
"_id": "55e5b32f3874c964cc3dfe2e",
"firstName": "xyz",
"lastName": "abc",
"socialStats": [],
"socialAuth": [
{
"screenName": "abc",
"userId": "12341234",
"_id": "55e5b3573874c964cc3dfe33",
"showStats": false,
"platformName": "Twitter"
},
{
"channelTitle": "xyz",
"channelId": "sdfgsdfgsdfg",
"_id": "55e5a040991c1321a5b9bd79",
"showStats": true,
"platformName": "Youtube"
}
]
};
You need to use _.remove() to remove the elements from array based on your condition.
Demo
var creatorObj = {
"_id": "55e5b32f3874c964cc3dfe2e",
"firstName": "xyz",
"lastName": "abc",
"socialStats": [{
"reach": 205976,
"_id": "asdfasdfasdf",
"profileUrl": null,
"engagements": 126,
"platformName": "Twitter"
}],
"socialAuth": [{
"screenName": "abc",
"userId": "12341234",
"_id": "55e5b3573874c964cc3dfe33",
"showStats": false,
"platformName": "Twitter"
}, {
"channelTitle": "xyz",
"channelId": "sdfgsdfgsdfg",
"_id": "55e5a040991c1321a5b9bd79",
"showStats": true,
"platformName": "Youtube"
}]
};
var arrList2 = _.pluck(_.where(creatorObj.socialAuth, {
'showStats': false
}), "platformName");
creatorObj.socialStats = _.remove(creatorObj.socialStats, function(n) {
return !_.includes(arrList2, n.platformName);
});
console.log(creatorObj);
document.write(JSON.stringify(creatorObj));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>

Getting a variable from a multidimentional JSON array using Jquery

I am retrieving a multidimensional JSON array using JQUERY.
I need to print out various items from the array, but am having a hard time figuring out how to go through the array and get these items so I can insert them into the HTML.
Here is an example of the array (this is what is taken from the jsonpage.php referenced below.
{
"count":1,
"total_count":1,
"contacts":[
{
"id":92840643,
"user_id":55536,
"first_name":"John",
"last_name":"Doe",
"full_name":"John Doe",
"initials":"JD",
"title":null,
"company":null,
"email":"john#doe.com",
"avatar":"https://graph.facebook.com/123454/picture?type=large",
"avatar_url":"https://graph.facebook.com/123454/picture?type=large",
"last_contacted":null,
"visible":true,
"twitter":null,
"facebook_url":null,
"linkedin_url":null,
"first_contacted":null,
"created_at":"2014-05-26T19:06:55Z",
"updated_at":"2014-05-26T19:12:42Z",
"hits":0,
"user_bucket_id":486405,
"team_parent_id":null,
"snoozed_at":null,
"snooze_days":null,
"groupings":[
{
"id":21554286,
"type":"Grouping::Location",
"name":"Johnson, NY",
"stub":"frisco tx",
"bucket_id":null,
"user_id":55536,
"domain_id":null,
"editable":null,
"conversable":null,
"locked":null,
"derived_from_id":null
},
{
"id":21553660,
"type":"Grouping::Bucket",
"name":"Top Customers",
"stub":"top customers",
"bucket_id":486405,
"user_id":55536,
"domain_id":null,
"editable":null,
"conversable":null,
"locked":null,
"derived_from_id":null,
"has_followups":true,
"num_days_to_followup":30,
"program_id":null
}
],
"email_addresses":[
"john#doe.com"
],
"tags":[
],
"contact_status":3,
"team_last_contacted":null,
"team_last_contacted_by":null,
"phone_numbers":[
],
"addresses":[
{
"_id":"538390cfcc0fb067d8000353",
"created_at":"2014-05-26T19:06:55Z",
"deleted_at":null,
"extra_data":{
"address_city":"Johnson",
"address_state":"NY",
"address_country":"United States"
},
"label":"Address",
"primary":null,
"remote_id":null,
"updated_at":"2014-05-26T19:06:55Z",
"username":null,
"value":"Johnson, NY\nUnited States"
}
],
"social_profiles":[
],
"websites":[
],
"custom_fields":[
{
"_id":"538390cfcc0fb067d8000354",
"custom_field_id":46639,
"deleted_at":null,
"label":"WeeklyNews",
"value":"YES"
},
{
"_id":"538390cfcc0fb067d8000355",
"custom_field_id":46640,
"deleted_at":null,
"label":"Current Credits",
"value":"142"
},
{
"_id":"538390cfcc0fb067d8000356",
"custom_field_id":46641,
"deleted_at":null,
"label":"Total Purchased Amount",
"value":"400"
},
{
"_id":"538390cfcc0fb067d8000357",
"custom_field_id":46642,
"deleted_at":null,
"label":"VDownloads",
"value":"112"
},
{
"_id":"538390cfcc0fb067d8000358",
"custom_field_id":46643,
"deleted_at":null,
"label":"AEDownloads",
"value":"9"
},
{
"_id":"538390cfcc0fb067d8000359",
"custom_field_id":46644,
"deleted_at":null,
"label":"ADownloads",
"value":"53"
},
{
"_id":"538390cfcc0fb067d800035a",
"custom_field_id":46638,
"deleted_at":null,
"label":"Last Login",
"value":"2014-05-25 23:14:19"
},
{
"_id":"538390cfcc0fb067d800035b",
"custom_field_id":46649,
"deleted_at":null,
"label":"Label",
"value":"Group1"
}
]
}
]
}
And here is the jquery success code:
$.post('/jsonpage.php', post_data, function(response) {
});
Now, if I put alert(response); within the function i.e.:
$.post('/jsonpage.php', post_data, function(response) {
alert(response);
});
Then, it 'does' alert the entire JSON string as listed above.
However, if I put this:
$.post('/jsonpage.php', post_data, function(response) {
alert(response.count);
});
Then, I get UNDEFINED in the alert box. I have tried a few different variables to 'alert' and they all come back undefined.
Thanks for your help!
Craig
response.total_count
response.contacts[0].id
response.contacts[0].groupings[0].stub
And so on.
Here are some ways of using the data in your json response. Hope it helps.
$.post('/jsonpage.php', post_data, function(response) {
if (!response.contacts || !response.contacts.length) {
alert("Error loading that/those contact(s)");
return;
}
for (var i=0, c; c = response.contacts[i]; i++) {
// c is each contact, do stuff with c
alert("That contact was created at " + c.created_at + " and last updated at " + c.updated_at);
var cities = [];
for (var j=0, a; a = c.addresses[j]; j++) {
// a refers to each address
cities.push(a.extra_data.address_city);
}
alert(c.full_name + " lives in " + cities.join(" and ") + ".");
for (var j=0, cf; cf = c.custom_fields[j]; j++) {
// cf is each custom_field
// build a form or something
// element label is cf.label
// element value is currently cf.value
var p = document.createElement("p");
p.appendChild(document.createTextNode(cf.label));
var el = document.createElement("input");
el.type = "text";
el.value = cf.value;
p.appendChild(el);
document.getElementById("someForm").appendChild(p);
}
}
});
Try this
var data = { "count": 1, "total_count": 1, "contacts": [{ "id": 92840643, "user_id": 55536, "first_name": "John", "last_name": "Doe", "full_name": "John Doe", "initials": "JD", "title": null, "company": null, "email": "john#doe.com", "avatar": "https://graph.facebook.com/123454/picture?type=large", "avatar_url": "https://graph.facebook.com/123454/picture?type=large", "last_contacted": null, "visible": true, "twitter": null, "facebook_url": null, "linkedin_url": null, "first_contacted": null, "created_at": "2014-05-26T19:06:55Z", "updated_at": "2014-05-26T19:12:42Z", "hits": 0, "user_bucket_id": 486405, "team_parent_id": null, "snoozed_at": null, "snooze_days": null, "groupings": [{ "id": 21554286, "type": "Grouping::Location", "name": "Johnson, NY", "stub": "frisco tx", "bucket_id": null, "user_id": 55536, "domain_id": null, "editable": null, "conversable": null, "locked": null, "derived_from_id": null }, { "id": 21553660, "type": "Grouping::Bucket", "name": "Top Customers", "stub": "top customers", "bucket_id": 486405, "user_id": 55536, "domain_id": null, "editable": null, "conversable": null, "locked": null, "derived_from_id": null, "has_followups": true, "num_days_to_followup": 30, "program_id": null}], "email_addresses": ["john#doe.com"], "tags": [], "contact_status": 3, "team_last_contacted": null, "team_last_contacted_by": null, "phone_numbers": [], "addresses": [{ "_id": "538390cfcc0fb067d8000353", "created_at": "2014-05-26T19:06:55Z", "deleted_at": null, "extra_data": { "address_city": "Johnson", "address_state": "NY", "address_country": "United States" }, "label": "Address", "primary": null, "remote_id": null, "updated_at": "2014-05-26T19:06:55Z", "username": null, "value": "Johnson, NY\nUnited States"}], "social_profiles": [], "websites": [], "custom_fields": [{ "_id": "538390cfcc0fb067d8000354", "custom_field_id": 46639, "deleted_at": null, "label": "WeeklyNews", "value": "YES" }, { "_id": "538390cfcc0fb067d8000355", "custom_field_id": 46640, "deleted_at": null, "label": "Current Credits", "value": "142" }, { "_id": "538390cfcc0fb067d8000356", "custom_field_id": 46641, "deleted_at": null, "label": "Total Purchased Amount", "value": "400" }, { "_id": "538390cfcc0fb067d8000357", "custom_field_id": 46642, "deleted_at": null, "label": "VDownloads", "value": "112" }, { "_id": "538390cfcc0fb067d8000358", "custom_field_id": 46643, "deleted_at": null, "label": "AEDownloads", "value": "9" }, { "_id": "538390cfcc0fb067d8000359", "custom_field_id": 46644, "deleted_at": null, "label": "ADownloads", "value": "53" }, { "_id": "538390cfcc0fb067d800035a", "custom_field_id": 46638, "deleted_at": null, "label": "Last Login", "value": "2014-05-25 23:14:19" }, { "_id": "538390cfcc0fb067d800035b", "custom_field_id": 46649, "deleted_at": null, "label": "Label", "value": "Group1"}]}] };
alert(data["contacts"][0]["id"]);
//get count
alert(data["count"]); //1
//get first contacts data
data["contacts"][0]["id"] //retruns 92840643
//do same for others to get data

Categories

Resources