Remove parent array and object elements from json - Strapi - arrays

Currently building an API with Strapi with the model of a blog post such that each Post has a Title, Slug, Content, and user Relation.
What data looks like:
{
"data": [
{
"id": 1,
"attributes": {
"title": "Test1",
"createdAt": "2022-07-24T18:33:34.195Z",
"updatedAt": "2022-07-24T18:33:34.863Z",
"publishedAt": "2022-07-24T18:33:34.861Z",
"user": {
"data": {
"id": 1,
"attributes": {
"username": "xyz",
"email": "xyz#gmail.com",
"provider": "local",
"confirmed": false,
"blocked": false,
"createdAt": "2022-07-24T14:28:16.466Z",
"updatedAt": "2022-07-24T14:29:00.126Z"
}
}
}
}
}
],
}
What I want it to look like:
{
{
"id": 1,
"title": "Test1",
"createdAt": "2022-07-24T18:33:34.195Z",
"updatedAt": "2022-07-24T18:33:34.863Z",
"publishedAt": "2022-07-24T18:33:34.861Z",
"user": {
"id": 1,
"username": "xyz",
"email": "xyz#gmail.com",
"provider": "local",
"confirmed": false,
"blocked": false,
"createdAt": "2022-07-24T14:28:16.466Z",
"updatedAt": "2022-07-24T14:29:00.126Z"
}
}
}
By default, the data is wrapped in unnecessarily tiresome arrays and objects and any attempt to edit the scehma.json causes the API to crash.
How can I fix this?

you can try this solution :
const x = {
"data": [
{
"id": 1,
"attributes": {
"title": "Test1",
"createdAt": "2022-07-24T18:33:34.195Z",
"updatedAt": "2022-07-24T18:33:34.863Z",
"publishedAt": "2022-07-24T18:33:34.861Z",
"user": {
"data": {
"id": 1,
"attributes": {
"username": "xyz",
"email": "xyz#gmail.com",
"provider": "local",
"confirmed": false,
"blocked": false,
"createdAt": "2022-07-24T14:28:16.466Z",
"updatedAt": "2022-07-24T14:29:00.126Z"
}
}
}
}
}
],
}
const data = x.data[0]
const users = {id: data.attributes.user.data.id , ...data.attributes.user.data.attributes}
const result = {id: data.id , title: data.attributes.title , createdAt: data.attributes.createdAt , updatedAt: data.attributes.updatedAt , publishedAt: data.attributes.publishedAt , user: users }
```

Related

Filter Out duplicate arrays and return the unique array in mongodb aggregation

I have come a long way in structuring into the following mongodb data collection, but i couldn't finish the aggregation stage,
{
"test": [
{
"_id": "60014aee808bc5033b45c222",
"name": "a rogram",
"companyName": "company NAme",
"website": "https://www.example.comn",
"loginUrl": "https://www.example.comn",
"description": null,
"createdBy": "5fe5cbcdb9ac0f001dccfadf",
"createdAt": "2021-01-15T07:57:34.499Z",
"updatedAt": "2021-01-15T13:09:09.417Z",
"__v": 0,
"address": null,
"affiliatePlatform": "asdf",
"brands": 3,
"newList": [
{
"_id": "5feee63fd86250046d64d02e",
"name": "NEWBRAND",
"affiliateProgram": "60014aee808bc5033b45c222",
"operator": "scdscacscasc",
"description": null,
"established": "2021-01-20T12:39:25.000Z",
"createdAt": "2021-01-01T09:07:11.180Z",
"updatedAt": "2021-01-15T12:39:36.898Z",
"__v": 0,
"updatedBy": null,
"newPMBList": [
{
"_id": "5feee78ead36a5052cdaddc0",
"projectMarket": "5feb10c4906c880076ce5fa6",
"brand": "5feee63fd86250046d64d02e",
"createdAt": "2021-01-01T09:12:46.588Z",
"updatedAt": "2021-01-01T09:12:46.588Z",
"__v": 0,
"newPMList": [
{
"_id": "5feb10c4906c880076ce5fa6",
"project": "5feb10b6906c880076ce5fa5",
"market": "5feb0f44906c880076ce5f9d",
"url": "https://www.example.com/place",
"createdAt": "2020-12-29T11:19:32.945Z",
"updatedAt": "2020-12-29T11:19:32.945Z",
"__v": 0
}
]
}
]
},
{
"_id": "5ff07fce63da300174a014bb",
"name": "Nike",
"operator": "scdscacscasc",
"createdAt": "2021-01-02T14:14:38.607Z",
"updatedAt": "2021-01-15T08:05:09.475Z",
"__v": 0,
"description": "This is new afdkjnvlaf",
"established": "2021-01-27T08:02:38.000Z",
"updatedBy": null,
"affiliateProgram": "60014aee808bc5033b45c222",
"newPMBList": [
{
"_id": "5ff451891136a7006bc2b0eb",
"projectMarket": "5feb10c4906c880076ce5fa6",
"brand": "5ff07fce63da300174a014bb",
"createdAt": "2021-01-05T11:46:17.745Z",
"updatedAt": "2021-01-05T11:46:17.745Z",
"__v": 0,
"newPMList": [
{
"_id": "5feb10c4906c880076ce5fa6",
"project": "5feb10b6906c880076ce5fa5",
"market": "5feb0f44906c880076ce5f9d",
"url": "https://www.example.com/place",
"createdAt": "2020-12-29T11:19:32.945Z",
"updatedAt": "2020-12-29T11:19:32.945Z",
"__v": 0
}
]
}
]
},
{
"_id": "5fff0336d78339005812aaa4",
"name": "United Bank",
"affiliateProgram": "60014aee808bc5033b45c222",
"operator": "scdsc",
"description": "ascasccsac",
"established": null,
"createdAt": "2021-01-13T14:27:02.931Z",
"updatedAt": "2021-01-15T12:43:34.857Z",
"__v": 0,
"updatedBy": null,
"newPMBList": []
}
],
"projectsNumber": null
},
{
"_id": "6001923a1f1fb007437dc479",
"name": "Hotel Advertisement",
"companyName": "Atlas",
"website": "https://www.atlas.com",
"loginUrl": "https://www.atlas.com/luser/ogin",
"createdBy": "5fe5cbcdb9ac0f001dccfadf",
"createdAt": "2021-01-15T13:01:46.715Z",
"updatedAt": "2021-01-15T13:20:42.757Z",
"__v": 0,
"address": null,
"affiliatePlatform": "NetRefer",
"description": null,
"brands": 2,
"newList": [
{
"_id": "5ffff156f06d4700e255cde5",
"name": "Amazon",
"affiliateProgram": "6001923a1f1fb007437dc479",
"operator": "scdscacscasc",
"description": "vsdfvsfdv",
"established": null,
"createdAt": "2021-01-14T07:23:02.455Z",
"updatedAt": "2021-01-15T13:19:59.522Z",
"__v": 0,
"updatedBy": null,
"newPMBList": []
},
{
"_id": "60000d4c61316a01d2fbb1aa",
"name": "Toshiba",
"affiliateProgram": "6001923a1f1fb007437dc479",
"operator": "scdsc",
"description": "cvadfvfdvbfdav",
"established": null,
"createdAt": "2021-01-14T09:22:20.306Z",
"updatedAt": "2021-01-15T13:20:10.970Z",
"__v": 0,
"updatedBy": null,
"newPMBList": []
}
],
"projectsNumber": null
}
]
}
in the document above i would like to only return the distinct list of the newPMList along with the other data except the newList array like so:
"_id": "60014aee808bc5033b45c222",
"name": "21 Program",
"companyName": "Online Casino",
"website": "https://www.online.casinoe",
"loginUrl": "https://www.online.casino",
"description": null,
"createdBy": "5fe5cbcdb9ac0f001dccfadf",
"createdAt": "2021-01-15T07:57:34.499Z",
"updatedAt": "2021-01-15T13:09:09.417Z",
"__v": 0,
"address": null,
"affiliatePlatform": "Cellxpert",
"brands": 3,
"newPMList": [
{
"_id": "5feb10c4906c880076ce5fa6",
"project": "5feb10b6906c880076ce5fa5",
"market": "5feb0f44906c880076ce5f9d",
"url": "https://www.addissoftware.com/ethiopia",
"createdAt": "2020-12-29T11:19:32.945Z",
"updatedAt": "2020-12-29T11:19:32.945Z",
"__v": 0
}
]
per a document, but i couldn't any help is appreciated.
db.collection.aggregate([
{//Denormalize first level
"$unwind": "$newList"
},
{//Second nested level
"$unwind": "$newList.newPMBList"
},
{//Deep nested last level
"$unwind": "$newList.newPMBList.newPMList"
},
{
$group: {//Grouping back
"_id": null,
"newList": {
$push: "$newList.newPMBList.newPMList"
}
}
},
{
$project: {//Finding unique
newList: {
$setUnion: [
"$newList",
"$newList"
]
}
}
}
])
I suggest you to include other fields using first accumulator in group and preserve them in project.
You can simplify further as below
db.test.aggregate([
{
"$unwind": "$newList"
},
{
"$unwind": "$newList.newPMBList"
},
{
"$unwind": "$newList.newPMBList.newPMList"
},
{
$group: {
"_id": null,
"newList": {//addToSet keeps distinct
$addToSet: "$newList.newPMBList.newPMList"
}
}
}
])
Further, buy skipping one denormalisation, But it returns array of arrays.
db.test.aggregate([
{
"$unwind": "$newList"
},
{
"$unwind": "$newList.newPMBList"
},
{
$group: {
"_id": null,
"newList": {
$addToSet: "$newList.newPMBList.newPMList"
}
}
}
])
If you skip another level, it will add one more nested level in the result.

loopback Custom order by

I am using angularjs for frontend and loopback for backend and elastic search for the database.
I have a model with properties as:
"name": {
"type": "string",
"required": true
},
"mobileNumber": {
"type": "string",
"required": true
},
"email": {
"type": "string"
},
"message": {
"type": "string",
"required": true
},
"quantity": {
"type": "number",
"required": true
},
"price": {
"type": "number",
"required": true
},
"status": {
"type": "string",
"required": true,
"default": "open"
}
},
data as:
{
"_index": "XXXXXX",
"_type": "XXXXX",
"_id": "XXXXXXX",
"_version": 1,
"_score": 1,
"_source": {
"name": "aadil kirana",
"email": "aadil#gmail.com",
"message": "dfgfb dgfggf",
"quantity": 3434,
"price": 5454,
"status": "open",
"createdAt": "2017-12-19T14:53:41.727Z",
"updatedAt": "2017-12-19T14:53:41.727Z"
}
}
Status could be open, processing, close, reject and failure.
All I want is to get the data in the order where I can see all the open status data ordered by createdAt date,
then all the prcoessing status data ordered by createdAt dat
and so on....
I tried using loopback filters as:
filter = {
order: ['status ASC','createdAt DESC'],
};
but this gives me First all the close status data ordered by date, then all the open status data ordered by date and so on, that status ordered alphabetically.
Please help me to get the desired result.
You can add a new property to your data as statusOrder and define
1 -> open
2 -> close
...
and order by statusOrder instead of status when you are ordering status.
All I want is to get the data in the order where I can see all the
open status data ordered by createdAt date, then all the prcoessing
status data ordered by createdAt dat and so on....
A workaround for this could be to let Elasticsearch do the sort with custom order e.g. in this context the status could be ordered as open followed by processing followed by close followed by reject followed by failure. It can be done with Function Score Query. Some more insights could also be found here
Sample input data for bulk insert:
POST custom/sort/_bulk?pretty
{"index" : {"_index" : "custom"}}
{"status": "open", "createdAt": "2017-12-19T14:53:41.727Z"}
{"index" : {"_index" : "custom"}}
{"status": "open", "createdAt": "2017-12-18T14:53:41.727Z"}
{"index" : {"_index" : "custom"}}
{"status": "processing", "createdAt": "2017-12-19T14:53:41.727Z"}
{"index" : {"_index" : "custom"}}
{"status": "processing", "createdAt": "2017-12-17T14:53:41.727Z"}
{"index" : {"_index" : "custom"}}
{"status": "close", "createdAt": "2017-12-19T14:53:41.727Z"}
{"index" : {"_index" : "custom"}}
{"status": "close", "createdAt": "2017-12-19T15:53:41.727Z"}
{"index" : {"_index" : "custom"}}
{"status": "failure", "createdAt": "2017-12-19T10:53:41.727Z"}
{"index" : {"_index" : "custom"}}
{"status": "failure", "createdAt": "2017-12-19T14:59:41.727Z"}
{"index" : {"_index" : "custom"}}
{"status": "reject", "createdAt": "2017-12-19T14:53:40.727Z"}
{"index" : {"_index" : "custom"}}
{"status": "reject", "createdAt": "2017-12-19T14:53:41.727Z"}
Sample response from elastic search (without custom order):
Query:
GET custom/sort/_search?filter_path=took,hits.total,hits.hits._score,hits.hits._source
{
"took": 0,
"hits": {
"total": 10,
"hits": [
{
"_score": 1,
"_source": {
"status": "processing",
"createdAt": "2017-12-19T14:53:41.727Z"
}
},
{
"_score": 1,
"_source": {
"status": "close",
"createdAt": "2017-12-19T14:53:41.727Z"
}
},
{
"_score": 1,
"_source": {
"status": "reject",
"createdAt": "2017-12-19T14:53:40.727Z"
}
},
{
"_score": 1,
"_source": {
"status": "open",
"createdAt": "2017-12-18T14:53:41.727Z"
}
},
{
"_score": 1,
"_source": {
"status": "failure",
"createdAt": "2017-12-19T10:53:41.727Z"
}
},
{
"_score": 1,
"_source": {
"status": "failure",
"createdAt": "2017-12-19T14:59:41.727Z"
}
},
{
"_score": 1,
"_source": {
"status": "reject",
"createdAt": "2017-12-19T14:53:41.727Z"
}
},
{
"_score": 1,
"_source": {
"status": "open",
"createdAt": "2017-12-19T14:53:41.727Z"
}
},
{
"_score": 1,
"_source": {
"status": "processing",
"createdAt": "2017-12-17T14:53:41.727Z"
}
},
{
"_score": 1,
"_source": {
"status": "close",
"createdAt": "2017-12-19T15:53:41.727Z"
}
}
]
}
}
Query to mimic custom ordering :
GET custom/sort/_search?filter_path=took,hits.hits._id,hits.hits._score,hits.hits._source,hits.hits.sort
{
"query": {
"function_score": {
"boost_mode": "replace",
"query": {
"constant_score": {
"filter": {
"terms": {
"status.keyword": [
"open",
"processing",
"close",
"reject",
"failure"
]
}
}
}
},
"functions": [
{
"filter": {
"term": {
"status.keyword": "open"
}
},
"weight": 4
},
{
"filter": {
"term": {
"status.keyword": "processing"
}
},
"weight": 3
},
{
"filter": {
"term": {
"status.keyword": "close"
}
},
"weight": 2
},
{
"filter": {
"term": {
"status.keyword": "reject"
}
},
"weight": 1
},
{
"filter": {
"term": {
"status.keyword": "failure"
}
},
"weight": 0
}
]
}
},
"sort": [
{
"_score": {
"order": "desc"
},
"createdAt": {
"order": "asc"
}
}
]
}
Output (with custom order):
{
"took": 4,
"hits": {
"hits": [
{
"_id": "grOucmABwtSchlgLKlaV",
"_score": 4,
"_source": {
"status": "open",
"createdAt": "2017-12-18T14:53:41.727Z"
},
"sort": [
4,
1513608821727
]
},
{
"_id": "gbOucmABwtSchlgLKlaV",
"_score": 4,
"_source": {
"status": "open",
"createdAt": "2017-12-19T14:53:41.727Z"
},
"sort": [
4,
1513695221727
]
},
{
"_id": "hLOucmABwtSchlgLKlaV",
"_score": 3,
"_source": {
"status": "processing",
"createdAt": "2017-12-17T14:53:41.727Z"
},
"sort": [
3,
1513522421727
]
},
{
"_id": "g7OucmABwtSchlgLKlaV",
"_score": 3,
"_source": {
"status": "processing",
"createdAt": "2017-12-19T14:53:41.727Z"
},
"sort": [
3,
1513695221727
]
},
{
"_id": "hbOucmABwtSchlgLKlaV",
"_score": 2,
"_source": {
"status": "close",
"createdAt": "2017-12-19T14:53:41.727Z"
},
"sort": [
2,
1513695221727
]
},
{
"_id": "hrOucmABwtSchlgLKlaV",
"_score": 2,
"_source": {
"status": "close",
"createdAt": "2017-12-19T15:53:41.727Z"
},
"sort": [
2,
1513698821727
]
},
{
"_id": "ibOucmABwtSchlgLKlaV",
"_score": 1,
"_source": {
"status": "reject",
"createdAt": "2017-12-19T14:53:40.727Z"
},
"sort": [
1,
1513695220727
]
},
{
"_id": "irOucmABwtSchlgLKlaV",
"_score": 1,
"_source": {
"status": "reject",
"createdAt": "2017-12-19T14:53:41.727Z"
},
"sort": [
1,
1513695221727
]
},
{
"_id": "h7OucmABwtSchlgLKlaV",
"_score": 0,
"_source": {
"status": "failure",
"createdAt": "2017-12-19T10:53:41.727Z"
},
"sort": [
0,
1513680821727
]
},
{
"_id": "iLOucmABwtSchlgLKlaV",
"_score": 0,
"_source": {
"status": "failure",
"createdAt": "2017-12-19T14:59:41.727Z"
},
"sort": [
0,
1513695581727
]
}
]
}
}

AngularJS ng-repeat display json

I'm having the hardest time figuring out how to display the following JSON file in my Angularjs repeat.
for the following JSON results, I thought I could simply display the title in an ng-repeat with the following:
<div ng-repeat="x in results">
{{x.data[0].title}}
</div>
But I'm not seeing results.
Here is the JSON:
{
"data": [
{
"id": 1,
"title": "Temp Title",
"description": "Temp Description",
"created_at": {
"date": "2016-03-15 07:10:17.000000",
"timezone_type": 3,
"timezone": "UTC"
},
"updated_at": {
"date": "2016-03-15 07:10:17.000000",
"timezone_type": 3,
"timezone": "UTC"
},
"user": {
"data": {
"id": 29,
"displayName": "chris.nakea",
"email": "chris.nakea#freshconsulting.com",
"join_date": 1458025279,
"profile": {
"data": {
"id": 29,
"displayName": "chris.nakea",
"avatar": null,
"firstName": null,
"lastName": null,
"bio": null,
"city": null,
"zipcode": null,
"state": null,
"country": null,
"latitude": null,
"longitude": null,
"avatars": {
"data": [
{
"id": "default_avatar.png",
"filename": "default_avatar.png",
"url": "https://cdn.band.dev/common/images/common/default_avatar.png",
"created_at": {
"date": "2016-03-15 00:00:00.000000",
"timezone_type": 3,
"timezone": "UTC"
},
"images": {
"small": "https://cdn.band.dev/common/images/common/default_avatar_small.png",
"medium": "https://cdn.band.dev/common/images/common/default_avatar_medium.png",
"large": "https://cdn.band.dev/common/images/common/default_avatar_large.png"
}
}
]
},
"coverPhotos": {
"data": []
}
}
}
}
},
"category": {
"data": {
"id": 2,
"name": "Staff / Events",
"description": "Staff / Events",
"colorCode": "#242156",
"iconName": "icon-staff-events",
"iconCharacterCode": "c108"
}
},
"attachments": {
"data": [
{
"id": "1d3f96e2286c27ee599c9e49a0c33da0",
"filename": "man.jpg",
"url": "https://api.band.dev/v1/file/1d3f96e2286c27ee599c9e49a0c33da0",
"created_at": {
"date": "2016-03-15 07:10:17.000000",
"timezone_type": 3,
"timezone": "UTC"
},
"images": {
"small": "https://api.band.dev/v1/file/50af58b3d52d8629e9f5c4d0dcdd5181",
"medium": "https://api.band.dev/v1/file/51535d38f7b3cd82313eac2414059d83",
"large": "https://api.band.dev/v1/file/a7be1dada18e4041cf48aea377cafa29"
}
}
]
}
},
{
"id": 2,
"title": "Temp Title",
"description": "Temp Description",
"created_at": {
"date": "2016-03-15 07:12:00.000000",
"timezone_type": 3,
"timezone": "UTC"
},
"updated_at": {
"date": "2016-03-15 07:12:00.000000",
"timezone_type": 3,
"timezone": "UTC"
},
"user": {
"data": {
"id": 29,
"displayName": "chris.nakea",
"email": "chris.nakea#freshconsulting.com",
"join_date": 1458025279,
"profile": {
"data": {
"id": 29,
"displayName": "chris.nakea",
"avatar": null,
"firstName": null,
"lastName": null,
"bio": null,
"city": null,
"zipcode": null,
"state": null,
"country": null,
"latitude": null,
"longitude": null,
"avatars": {
"data": [
{
"id": "default_avatar.png",
"filename": "default_avatar.png",
"url": "https://cdn.band.dev/common/images/common/default_avatar.png",
"created_at": {
"date": "2016-03-15 00:00:00.000000",
"timezone_type": 3,
"timezone": "UTC"
},
"images": {
"small": "https://cdn.band.dev/common/images/common/default_avatar_small.png",
"medium": "https://cdn.band.dev/common/images/common/default_avatar_medium.png",
"large": "https://cdn.band.dev/common/images/common/default_avatar_large.png"
}
}
]
},
"coverPhotos": {
"data": []
}
}
}
}
},
"category": {
"data": {
"id": 2,
"name": "Staff / Events",
"description": "Staff / Events",
"colorCode": "#242156",
"iconName": "icon-staff-events",
"iconCharacterCode": "c108"
}
},
"attachments": {
"data": [
{
"id": "a93cf8df7b60686e7ca6884d0ce353c8",
"filename": "man2.jpg",
"url": "https://api.band.dev/v1/file/a93cf8df7b60686e7ca6884d0ce353c8",
"created_at": {
"date": "2016-03-15 07:12:00.000000",
"timezone_type": 3,
"timezone": "UTC"
},
"images": {
"small": "https://api.band.dev/v1/file/cd04551395a355f4792fb85833156741",
"medium": "https://api.band.dev/v1/file/4ff543cd8f5055bfecd703dedaee6d87",
"large": "https://api.band.dev/v1/file/5cdd9a0c3650228e0b93f9c6cd1404df"
}
}
]
}
}
]
}
You can just remove the datap[0] part and get the output
<div ng-repeat="x in results.data">
{{x.title}}
</div>
Output:
Temp Title
Temp Title
if you want to filter then you can do it by
<div ng-repeat="x in results.data | filter: { id: '1' }">
{{x.title}}
</div>
Output:
Temp Title
<div ng-repeat="item in data">{{item.title}}</div>
And in your controller, bind the json to the scope.
$scope.data = jsonData.data;
Here's a fiddle for you - jsFiddle
<div ng-repeat="x in results.data">
{{x.title}}
</div>
https://jsfiddle.net/nvqf8oo7/6/
Thank you all for responding. I finally figured out that the reason I wasn't seeing anything was because I am using ui.bootstrap's modal and I was out of scope.
I resolved this by moving the ng-repeat out of the modal, but I could have also tried to work with the modal scope itself.

Use a for-in loop to get data from a JSON object which is not an array

I'm trying to loop through the results of a JSON response and get the title of each article, however my hosting company mentioned the returned object is not an array, so I can't loop through the articles.
Currently it gives me an undefined on the length of the amount of articles.
How can I loop through the articles and get their titles?
I tried everything below, and finally read somewhere I could use a for-in loop.
So I was checking out this example here: http://www.w3schools.com/js/tryit.asp?filename=tryjs_object_for_in
However, I have no idea how to apply this loop on my data to get just the articles and then loop through these and get their properties.
JSON RESPONSE
{
"blog": {
"id": "1464",
"comments": true,
"url": "blogs\/magazine",
"rss": "blogs\/magazine.rss",
"title": "Taj Magazine",
"articles": {
"3748": {
"id": 3748,
"image": 7442452,
"url": "blogs\/magazine\/foodies-walhalla-2",
"title": "Foodies Walhalla 2",
"author": "",
"author_url": false,
"summary": "dit is de samenvatting tekst",
"content": "dit is het hele artikel",
"date": "2013-11-13 13:54:00",
"comments": [],
"comments_count": 0,
"tags": {
"foodies-walhalla": {
"id": "9794",
"url": "blogs\/magazine\/tagged\/foodies-walhalla",
"title": "Foodies Walhalla",
"count": "2"
},
"magazine": {
"id": "9744",
"url": "blogs\/magazine\/tagged\/magazine",
"title": "magazine",
"count": "6"
}
}
},
"3747": {
"id": 3747,
"image": 7442441,
"url": "blogs\/magazine\/foodies-walhalla-1",
"title": "Foodies Walhalla 1",
"author": "",
"author_url": false,
"summary": "f df gdsfg",
"content": "dsfgsdfgdf sdfg",
"date": "2013-11-13 11:22:00",
"comments": [],
"comments_count": 0,
"tags": {
"foodies-walhalla": {
"id": "9794",
"url": "blogs\/magazine\/tagged\/foodies-walhalla",
"title": "Foodies Walhalla",
"count": "2"
},
"magazine": {
"id": "9744",
"url": "blogs\/magazine\/tagged\/magazine",
"title": "magazine",
"count": "6"
}
}
},
"3744": {
"id": 3744,
"image": 7442425,
"url": "blogs\/magazine\/beauty-artikel-2",
"title": "Beauty artikel 2",
"author": "",
"author_url": false,
"summary": "beauty article 2",
"content": "dfg sfg sdfg sdfgd gdsf df gsdf gdsf g",
"date": "2013-11-13 11:21:00",
"comments": [],
"comments_count": 0,
"tags": {
"beauty": {
"id": "9792",
"url": "blogs\/magazine\/tagged\/beauty",
"title": "beauty",
"count": "2"
},
"healthy": {
"id": "9745",
"url": "blogs\/magazine\/tagged\/healthy",
"title": "healthy",
"count": "2"
},
"magazine": {
"id": "9744",
"url": "blogs\/magazine\/tagged\/magazine",
"title": "magazine",
"count": "6"
}
}
},
"3745": {
"id": 3745,
"image": 7442417,
"url": "blogs\/magazine\/love-life-1",
"title": "Love & Life 1",
"author": "",
"author_url": false,
"summary": "dfgdsfgd",
"content": "f gdf gdfgdfg dfgdsfgdsfgdsfg",
"date": "2013-11-13 11:21:00",
"comments": [],
"comments_count": 0,
"tags": {
"love-life": {
"id": "9793",
"url": "blogs\/magazine\/tagged\/love-life",
"title": "love & life",
"count": "2"
},
"magazine": {
"id": "9744",
"url": "blogs\/magazine\/tagged\/magazine",
"title": "magazine",
"count": "6"
}
}
},
"3746": {
"id": 3746,
"image": 7442388,
"url": "blogs\/magazine\/love-life-2",
"title": "Love & Life 2",
"author": "",
"author_url": false,
"summary": "dfkjghksdjfh gdskfjdj sdlkjfhdjfghdjklfsdfkjhg df gd ghdkjsfhgkjsd fg lkjdshklgdfh kjds glkjsdh kljdsfh",
"content": "dfkjghksdjfh gdskfjdj sdlkjfhdjfghdjklfsdfkjhg df gd ghdkjsfhgkjsd fg lkjdshklgdfh kjds glkjsdh kljdsfh",
"date": "2013-11-13 11:21:00",
"comments": [],
"comments_count": 0,
"tags": {
"love-life": {
"id": "9793",
"url": "blogs\/magazine\/tagged\/love-life",
"title": "love & life",
"count": "2"
},
"magazine": {
"id": "9744",
"url": "blogs\/magazine\/tagged\/magazine",
"title": "magazine",
"count": "6"
}
}
}
}
},
"request": {
"url": "http:\/\/taj-ringen.webshopapp.com\/blogs\/magazine\/?format=json",
"method": "get",
"ssl": false,
"get": {
"format": "json"
},
"post": [],
"device": {
"platform": "windows",
"type": "webkit",
"mobile": false
}
},
"template": "pages\/blog.rain",
"renderer": "json"
}
JAVASCRIPT
<div id="loadstatus"></div>
<script type="text/javascript" language="javascript">
var newresult = '';
$.ajax({
type: "GET",
url: "http://taj-ringen.webshopapp.com/blogs/magazine/?format=json",
data: "",
dataType: "json",
success: function (mydata) {
console.log('load successful');
console.log('mydata.blog.articles.length: ' + mydata.blog.articles.length); //'undefined' error
for (var i = 0; i < mydata.blog.articles.length; i++) {
newresult += mydata.blog.articles[i].title;
}
}
});
</script>
I also had a look at this post: Convert Object to JSON string
tried the jQuery.parseJSON function
console.log(mydata);
var tmp = jQuery.parseJSON(mydata);
console.log(tmp);
console.log('tmp.blog.articles.length: ' + tmp.blog.articles.length);
But there I get an error Uncaught SyntaxError: Unexpected token o on line jquery-1.10.2.min.js:4
tried the $.map function
var array = $.map(mydata, function (e) {
return [$.map(e, function (v) {
return v;
})];
});
console.log(array);
console.log('tmp.blog.articles.length: ' + array.blog.articles.length);
Here I get Uncaught TypeError: Cannot use 'in' operator to search for '14' in pages/blog.rain on line jquery-1.10.2.min.js:4
What I'm trying to to is convert the object that is returned by the site and be able to loop through it.
Iterate through the article object, pulling out the keys associated with each article using the method described in the below post:
How to list the properties of a JavaScript object
You could also use the following loop:
for(var article in blog.articles) {
console.log(blog.articles[article].title);
}

How Can I Filter this JSON in Backbone?

I populated data from two separate mongodb schemas into an object below:
They are user and article. How can I filter/sort so I can find articles by user._id in backbone?
This is for a single page blog type site in which each user has their own articles.
I was looking at _.filter and _.where functions in underscore, but am still new to this. Any help is appreciated. Thanks.
Here is an example on my server of what im trying to build (was done with embedded schema):
http://kevg.co:3700/demo1
and backbone model/view/collection code is here:
http://kevg.co:3700/javascripts/demoj17.js
//Individual Model
{
"user": {
"username": "ho",
"email": "hom#gmail.com",
"_id": "51be709a148846ec25000007"
},
"name": "money",
"articlebody": "",
"_id": "51c1033283376a5808000002",
"__v": 0,
"createdAt": "2013-06-19T01:02:42.424Z"
},
//Rest of data
{
"user": {
"username": "kev",
"email": "kevo#o.com",
"_id": "51be6fe9148846ec25000001"
},
"name": "bob",
"articlebody": "",
"_id": "51c89ab47596ef1018000001",
"__v": 0,
"createdAt": "2013-06-24T19:15:00.835Z"
},
{
"user": {
"username": "kev",
"email": "kevo#o.com",
"_id": "51be6fe9148846ec25000001"
},
"name": "sasa",
"articlebody": "sajdja",
"_id": "51c8a3bf341eb4141f000001",
"__v": 0,
"createdAt": "2013-06-24T19:53:35.233Z"
}
I'd have a collection of users as well as a collection of articles.
To get the collection of articles a specific user has posted, you could perform something akin to:
// theUser would be the user selected
articlesCollection.where({'User': theUser});
Thanks, Loamhoof for pointing out the reduction.
Note, your User model could also hold a collection of Articles the user has posted.
Assuming your data as given below
var data = [{
"user": {
"username": "ho",
"email": "hom#gmail.com",
"_id": "51be709a148846ec25000007"
},
"name": "money",
"articlebody": "",
"_id": "51c1033283376a5808000002",
"__v": 0,
"createdAt": "2013-06-19T01:02:42.424Z"
}, {
"user": {
"username": "kev",
"email": "kevo#o.com",
"_id": "51be6fe9148846ec25000001"
},
"name": "bob",
"articlebody": "",
"_id": "51c89ab47596ef1018000001",
"__v": 0,
"createdAt": "2013-06-24T19:15:00.835Z"
}, {
"user": {
"username": "kev",
"email": "kevo#o.com",
"_id": "51be6fe9148846ec25000001"
},
"name": "sasa",
"articlebody": "sajdja",
"_id": "51c8a3bf341eb4141f000001",
"__v": 0,
"createdAt": "2013-06-24T19:53:35.233Z"
}];
you can use the filter function in Array or the one in underscore to filter the data
function getArticles(userName) {
return _.filter(data, function (item) {
return item.user.username == userName; // give the property to be used for filtering
});
}
var kevArticles = getArticles("kev");
var hoArticles = getArticles("ho");
Or you can use a groupBy in underscore to group the data with respect to the user
function groupByUserName(){
return _.groupBy(data, function (item) {
return item.user.username; // give the property to be used for filtering
});
}
var groupedData = groupByUserName();
This will make it in the format given below
{
"ho": [{
"user": {
"username": "ho",
"email": "hom#gmail.com",
"_id": "51be709a148846ec25000007"
},
"name": "money",
"articlebody": "",
"_id": "51c1033283376a5808000002",
"__v": 0,
"createdAt": "2013-06-19T01:02:42.424Z"
}],
"kev": [{
"user": {
"username": "kev",
"email": "kevo#o.com",
"_id": "51be6fe9148846ec25000001"
},
"name": "bob",
"articlebody": "",
"_id": "51c89ab47596ef1018000001",
"__v": 0,
"createdAt": "2013-06-24T19:15:00.835Z"
}, {
"user": {
"username": "kev",
"email": "kevo#o.com",
"_id": "51be6fe9148846ec25000001"
},
"name": "sasa",
"articlebody": "sajdja",
"_id": "51c8a3bf341eb4141f000001",
"__v": 0,
"createdAt": "2013-06-24T19:53:35.233Z"
}]

Resources