Related
i have a json returned from an api that shows latest discussions from a forum..
the url that display the json output is like:
https://example.com/api/discussions?isApproved=true&exists=true&sort=-lastPostedAt
and this is the json output:
"links": {
"first": "http://localhost/flarum/public/api/discussions?isApproved=true\u0026exists=true\u0026sort=-lastPostedAt",
"next": "http://localhost/flarum/public/api/discussions?isApproved=true\u0026exists=true\u0026sort=-lastPostedAt\u0026page%5Boffset%5D=20"
},
"data": [
{
"type": "discussions",
"id": "46",
"attributes": {
"title": "footer",
"slug": "46-footer",
"commentCount": 1,
"participantCount": 1,
"createdAt": "2021-09-20T07:14:18+00:00",
"lastPostedAt": "2021-09-20T07:14:18+00:00",
"lastPostNumber": 1,
"canReply": true,
"canRename": true,
"canDelete": true,
"canHide": true,
"lastReadAt": "2021-09-20T07:14:20+00:00",
"lastReadPostNumber": 1,
"isApproved": true,
"canTag": true,
"subscription": null,
"isLocked": false,
"canLock": true
},
"relationships": { "user": { "data": { "type": "users", "id": "1" } }, "lastPostedUser": { "data": { "type": "users", "id": "1" } }, "tags": { "data": [{ "type": "tags", "id": "2" }] } }
},
{
"type": "discussions",
"id": "45",
"attributes": {
"title": "fhgfhfg",
"slug": "45-fhgfhfg",
"commentCount": 2,
"participantCount": 1,
"createdAt": "2021-09-19T16:07:37+00:00",
"lastPostedAt": "2021-09-19T23:04:00+00:00",
"lastPostNumber": 2,
"canReply": true,
"canRename": true,
"canDelete": true,
"canHide": true,
"lastReadAt": "2021-09-19T23:04:02+00:00",
"lastReadPostNumber": 2,
"isApproved": true,
"canTag": true,
"subscription": null,
"isLocked": false,
"canLock": true
},
"relationships": { "user": { "data": { "type": "users", "id": "1" } }, "lastPostedUser": { "data": { "type": "users", "id": "1" } }, "tags": { "data": [{ "type": "tags", "id": "2" }] } }
},
{
"type": "discussions",
"id": "39",
"attributes": {
"title": "Discussion",
"slug": "39-discussion",
"commentCount": 21,
"participantCount": 1,
"createdAt": "2021-05-22T11:06:43+00:00",
"lastPostedAt": "2021-09-04T12:49:32+00:00",
"lastPostNumber": 28,
"canReply": true,
"canRename": true,
"canDelete": true,
"canHide": true,
"lastReadAt": "2021-09-04T12:49:34+00:00",
"lastReadPostNumber": 28,
"isApproved": true,
"canTag": true,
"subscription": null,
"isLocked": false,
"canLock": true
},
"relationships": { "user": { "data": { "type": "users", "id": "1" } }, "lastPostedUser": { "data": { "type": "users", "id": "1" } }, "tags": { "data": [{ "type": "tags", "id": "1" }] } }
}
what i want to do is to have something like "related content" based on a discussion title. For example if i have this title "lets talk about cars", the json must shows all the discussions related to this title.
is this possible?
You can take the data from json and just filter the content inside
const filteredResults = yourJsonResponse.data.filter(item => item.attributes.title === 'lets talk about cars')
This won't be a good idea. as you're getting paginated list with limit(like per page 20/30). if you're using js you can use js filter for getting related content. But as i said. that filer will be done based on your current page data, not all data. it's better to use another api end for related content from large data..
I wont to connect two collection so as to workouts._id had an assigned value exercise.name.
first collection "workouts":
{
"_id": {
"$oid": "60ffbd531b1cba41e8a7fde3"
},
"id_user": {
"$oid": "60fd50ee1e9d064a5cee0bec"
},
"date": {
"$date": "2021-05-20T22:00:00.000Z"
},
"name": "wielki bicek",
"workouts": [{
"_id": {
"$oid": "60e07e588a2f1946f895475f"
},
"parts": [{
"_id": {
"$oid": "60ffbd531b1cba41e8a7fde5"
},
"weight": "30",
"repeating": "10"
}]
}, {
"_id": {
"$oid": "60e07e588a2f1946f895475f"
},
"parts": [{
"_id": {
"$oid": "60ffbd531b1cba41e8a7fde9"
},
"weight": "30",
"repeating": "10"
}, {
"_id": {
"$oid": "60ffbd531b1cba41e8a7fdea"
},
"weight": "30",
"repeating": "10"
}]
}],
"__v": 0
}
second collection "exercises":
{
"_id": {
"$oid": "60e07e588a2f1946f895475f"
},
"name": "Wyciskanie sztangi",
"image": "uploads\\2021-07-03T15-12-24.173Z-test.gif",
"type": "force",
"groupMuscle": {
"$oid": "60daf099c1aaa20b4cfdf0fa"
},
"instruction": "Opierając tułów znazewnątrz.",
"__v": 0
}
I have one collection that I want to run nested aggregation on this, but I don't know how to run this operation.
$unwind unwind workouts
$lookup lookpup exercises
$addFileds get first item
$addFileds get only name field
$project remove useless field
$group group by original id
db.workouts.aggregate([
{
"$unwind": "$workouts"
},
{
"$lookup": {
"from": "exercises",
pipeline: [
{
"$project": {
name: 1
}
}
],
"localField": "workouts._id",
"foreignField": "_id",
"as": "names"
}
},
{
"$addFields": {
"workouts.i": {
"$first": "$names"
}
}
},
{
"$addFields": {
"workouts.name": "$workouts.i.name"
}
},
{
"$project": {
"names": 0,
"workouts.i": 0
}
},
{
"$group": {
"_id": {
"_id": "$_id",
"id_user": "$id_user",
"date": "$date",
"name": "$name"
},
"workouts": {
$push: "$workouts"
}
}
}
])
mongoplayground
When I use JSON.parse(myJSONString) the result is not a valid JSON file. I'm in an nodejs environment. Any Ideas what I can fix in my code? I user XML2JS to converte an XML Api call to JS.
I have printed out the results and already dived deeper into JSON.parse but didn't find further information...
exports.getStations = functions.https.onCall(async (data) => {
let stations
await axios.get(encodeURI(`XMLAPi`))
.then(async (response) => {
parseString(response.data, (err, result) => {
stations = JSON.stringify(result)
console.log(stations) //First console.log
})
})
.catch((error) => {
console.log(error)
})
console.log(JSON.parse(stations)) //Second console.log
return JSON.parse(stations)
})
Result for first console.log (valid JSON but String):
{"itdRequest":{"$":{"xsi:noNamespaceSchemaLocation":"itd.xsd","language":"DE","sessionID":"EfaOpenServiceT_2882840828","client":"axios/0.19.0","serverID":"EfaOpenServiceT_","clientIP":"127.0.0.1","version":"10.3.5.46","virtDir":"static02","xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance"},"itdStopFinderRequest":{"$":{"requestID":"1"},"itdOdv":{"$":{"type":"any","usage":"sf","anyObjFilter":"42"},"itdOdvPlace":{"$":{"state":"empty"},"odvPlaceElem":""},"itdOdvName":{"$":{"state":"list"},"itdMessage":{"$":{"type":"error","module":"BROKER","code":"-8011"}},"odvNameElem":[{"_":"Mettmann, Stadtwald S","$":{"value":"0:1","selected":"1","listIndex":"0","streetName":"","omc":"5158024","placeID":"5","x":"6987248.99348","y":"51250980.94198","mapName":"WGS84","id":"20019083","anyType":"stop","anyTypeSort":"2","nameKey":"","locality":"Mettmann","postCode":"","objectName":"Stadtwald S","buildingName":"","buildingNumber":"","matchQuality":"235","stateless":"20019083"}},{"_":"Mettmann, ME-Zentrum S","$":{"value":"1:2","selected":"0","listIndex":"1","streetName":"","omc":"5158024","placeID":"5","x":"6979002.45917","y":"51249372.83702","mapName":"WGS84","id":"20019020","anyType":"stop","anyTypeSort":"2","nameKey":"","locality":"Mettmann","postCode":"","objectName":"ME-Zentrum S","buildingName":"","buildingNumber":"","matchQuality":"234","stateless":"20019020"}},{"_":"Mettmann, Neanderthal S","$":{"value":"2:3","selected":"0","listIndex":"2","streetName":"","omc":"5158024","placeID":"5","x":"6953346.57466","y":"51227837.93128","mapName":"WGS84","id":"20019191","anyType":"stop","anyTypeSort":"2","nameKey":"","locality":"Mettmann","postCode":"","objectName":"Neanderthal S","buildingName":"","buildingNumber":"","matchQuality":"234","stateless":"20019191"}}],"odvNameInput":"mettmann"},"genAttrList":{"genAttrElem":[{"name":"anyObjFilter","value":"STOP"},{"name":"anyObjFilter","value":"ADDRESS"},{"name":"anyObjFilter","value":"POI"}]}},"itdDateTime":{"$":{"ttpFrom":"20190601","ttpTo":"20191231"},"itdDate":{"$":{"day":"10","month":"8","year":"2019","weekday":"7"}},"itdTime":{"$":{"hour":"16","minute":"4"}}}}}}
Result for second console.log (invalid JSON after parse):
Object {
"data": Object {
"itdRequest": Object {
"$": Object {
"client": "axios/0.19.0",
"clientIP": "127.0.0.1",
"language": "DE",
"serverID": "EfaOpenServiceT_",
"sessionID": "EfaOpenServiceT_2882840828",
"version": "10.3.5.46",
"virtDir": "static02",
"xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"xsi:noNamespaceSchemaLocation": "itd.xsd",
},
"itdStopFinderRequest": Object {
"$": Object {
"requestID": "1",
},
"itdDateTime": Object {
"$": Object {
"ttpFrom": "20190601",
"ttpTo": "20191231",
},
"itdDate": Object {
"$": Object {
"day": "10",
"month": "8",
"weekday": "7",
"year": "2019",
},
},
"itdTime": Object {
"$": Object {
"hour": "16",
"minute": "4",
},
},
},
"itdOdv": Object {
"$": Object {
"anyObjFilter": "42",
"type": "any",
"usage": "sf",
},
"genAttrList": Object {
"genAttrElem": Array [
Object {
"name": "anyObjFilter",
"value": "STOP",
},
Object {
"name": "anyObjFilter",
"value": "ADDRESS",
},
Object {
"name": "anyObjFilter",
"value": "POI",
},
],
},
"itdOdvName": Object {
"$": Object {
"state": "list",
},
"itdMessage": Object {
"$": Object {
"code": "-8011",
"module": "BROKER",
"type": "error",
},
},
"odvNameElem": Array [
Object {
"$": Object {
"anyType": "stop",
"anyTypeSort": "2",
"buildingName": "",
"buildingNumber": "",
"id": "20019083",
"listIndex": "0",
"locality": "Mettmann",
"mapName": "WGS84",
"matchQuality": "235",
"nameKey": "",
"objectName": "Stadtwald S",
"omc": "5158024",
"placeID": "5",
"postCode": "",
"selected": "1",
"stateless": "20019083",
"streetName": "",
"value": "0:1",
"x": "6987248.99348",
"y": "51250980.94198",
},
"_": "Mettmann, Stadtwald S",
},
Object {
"$": Object {
"anyType": "stop",
"anyTypeSort": "2",
"buildingName": "",
"buildingNumber": "",
"id": "20019020",
"listIndex": "1",
"locality": "Mettmann",
"mapName": "WGS84",
"matchQuality": "234",
"nameKey": "",
"objectName": "ME-Zentrum S",
"omc": "5158024",
"placeID": "5",
"postCode": "",
"selected": "0",
"stateless": "20019020",
"streetName": "",
"value": "1:2",
"x": "6979002.45917",
"y": "51249372.83702",
},
"_": "Mettmann, ME-Zentrum S",
},
Object {
"$": Object {
"anyType": "stop",
"anyTypeSort": "2",
"buildingName": "",
"buildingNumber": "",
"id": "20019191",
"listIndex": "2",
"locality": "Mettmann",
"mapName": "WGS84",
"matchQuality": "234",
"nameKey": "",
"objectName": "Neanderthal S",
"omc": "5158024",
"placeID": "5",
"postCode": "",
"selected": "0",
"stateless": "20019191",
"streetName": "",
"value": "2:3",
"x": "6953346.57466",
"y": "51227837.93128",
},
"_": "Mettmann, Neanderthal S",
},
],
"odvNameInput": "mettmann",
},
"itdOdvPlace": Object {
"$": Object {
"state": "empty",
},
"odvPlaceElem": "",
},
},
},
},
},
}
You are already converting to string as a parsestring function. But it's also converting to JSON.stringify().
You can try check this value
let stations = await axios.get(encodeURI(`XMLAPi`));
console.log(JSON.stringify(stations.data)) // What is value??
Suppose I have the following json file and I would like to return the 'existing.primaryBundle.products' array preferrably with lodash:
{
"existing": {
"hasPlatinum": false,
"primaryBundle": {
"id": "2008",
"name": "TV - Entertainment, Sport",
"products": [
{
"name": "Entertainment",
"id": "100",
"price": 2600,
"gifted": false
},
{
"name": "Sport",
"id": "107",
"price": 2500,
"gifted": false,
"swappableProducts": [
{
"name": "Movies",
"id": "105",
"price": 2000,
"gifted": false
}
]
}
]
},
"extrasBundle": {
"id": "131",
"name": "Optional Extras - MUTV (Sports), LFCTV (Sports), Chelsea TV (Sports)",
"products": [
{
"name": "MUTV (Sports)",
"id": "665",
"price": 0,
"gifted": false
},
{
"name": "LFCTV (Sports)",
"id": "666",
"price": 0,
"gifted": false
},
{
"name": "Chelsea TV (Sports)",
"id": "667",
"price": 0,
"gifted": false
}
]
}
}
}
I have tried lodash and use this statement:
list2 = _.pick(existing,'primaryBundle.products')
But this returns an error and not the wanted result. How can I select this products array?
you could use _.get(nameOfObject, 'existing.primaryBundle.products') of course you would need to name your object like I've done below with sampleObject;
check out the lodash docs too
const sampleObject = {
"existing": {
"hasPlatinum": false,
"primaryBundle": {
"id": "2008",
"name": "TV - Entertainment, Sport",
"products": [{
"name": "Entertainment",
"id": "100",
"price": 2600,
"gifted": false
}, {
"name": "Sport",
"id": "107",
"price": 2500,
"gifted": false,
"swappableProducts": [{
"name": "Movies",
"id": "105",
"price": 2000,
"gifted": false
}]
}]
},
"extrasBundle": {
"id": "131",
"name": "Optional Extras - MUTV (Sports), LFCTV (Sports), Chelsea TV (Sports)",
"products": [{
"name": "MUTV (Sports)",
"id": "665",
"price": 0,
"gifted": false
}, {
"name": "LFCTV (Sports)",
"id": "666",
"price": 0,
"gifted": false
}, {
"name": "Chelsea TV (Sports)",
"id": "667",
"price": 0,
"gifted": false
}]
}
}
}
console.log(_.get(sampleObject, 'existing.primaryBundle.products'));
The main reason why it returns an error is because existing is not a global scoped object, you have to assign object to some variable like const obj = {...} and then pass the parameter to _pick method as obj.existing, yet I don't see a reason to use lodash in here, you can just reference the path to that object directly.
This question already has answers here:
Sort array of objects by string property value
(57 answers)
Closed 8 years ago.
I have this array and I was wondering if I could sort it with the properties comments.count and likes.count separately.
For example I could just have a function to call using likes.count parameter or comments.count parameter.
{
"attribution": null,
"tags": [
],
"type": "",
"location": null,
"comments": {
"count": 2,
"data": [
{
"created_time": "1385670850",
"text": "Holy shit",
"from": {
"username": "someone",
"profile_picture": "http://url.com/profiles/profile_191120775_75sq_1365830292.jpg",
"id": "191120775"
},
"id": "599372997379438683"
},
{
"created_time": "1385680581",
"text": "",
"from": {
"username": "someone",
"profile_picture": "http://url.com/profiles/profile_1523167_75sq_1389544912.jpg",
"id": "1523167"
},
"id": "599454624038205610"
}
]
},
"likes": {
"count": 6,
"data": [
{
"username": "someone",
"profile_picture": "http://url.com/profiles/profile_2169761_75sq_1389075971.jpg",
"id": "2169761"
},
{
"username": "rashmityagi",
"profile_picture": "http://url.com/profiles/profile_393770264_75sq_1388911033.jpg",
"id": "393770264"
},
{
"username": "tylerferweda",
"profile_picture": "http://url.com/profiles/profile_191120775_75sq_1365830292.jpg",
"id": "191120775"
},
{
"username": "cbolts",
"profile_picture": "http://url.com/profiles/profile_1523167_75sq_1389544912.jpg",
"id": "1523167"
}
]
}
},
{
"attribution": null,
"tags": [
],
"type": "",
"location": null,
"comments": {
"count": 10,
"data": [
{
"created_time": "1385670850",
"text": "Holy shit",
"from": {
"username": "someone",
"profile_picture": "http://url.com/profiles/profile_191120775_75sq_1365830292.jpg",
"id": "191120775"
},
"id": "599372997379438683"
},
{
"created_time": "1385680581",
"text": "",
"from": {
"username": "someone",
"profile_picture": "http://url.com/profiles/profile_1523167_75sq_1389544912.jpg",
"id": "1523167"
},
"id": "599454624038205610"
}
]
},
"likes": {
"count": 20,
"data": [
{
"username": "someone",
"profile_picture": "http://url.com/profiles/profile_2169761_75sq_1389075971.jpg",
"id": "2169761"
},
{
"username": "rashmityagi",
"profile_picture": "http://url.com/profiles/profile_393770264_75sq_1388911033.jpg",
"id": "393770264"
},
{
"username": "tylerferweda",
"profile_picture": "http://url.com/profiles/profile_191120775_75sq_1365830292.jpg",
"id": "191120775"
},
{
"username": "cbolts",
"profile_picture": "http://url.com/profiles/profile_1523167_75sq_1389544912.jpg",
"id": "1523167"
}
]
}
},
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
json_array.sort(function(a, b) {
if(a.comments.count < b.comments.count) {
return -1;
}
if(a.comments.count > b.comments.count) {
return 1;
}
return 0;
});
You can also modify it for likes.count
Underscore.js provides great utility functions for working with arrays and objects. For your case you could use _.sortBy(...) See http://underscorejs.org/#sortBy for more details. For simple object properties it is enough to specify the object property name als last parameter.