I've generated some news items from a laravel API output, i display these on a angular 4 cli project. I noticed the items aren't on descending order though and I'm trying to fix this on the client side. Check it out, this is what I've got.
This is my JSON output from the api:
{
"post": [
{
"id": 17,
"creator": null,
"title": "Test artikel 4",
"content": "<p>Dit is een test artikel voor het nieuws.</p>",
"tags": null,
"photo": "website/uploads/",
"sticky": 0,
"created_at": 1506000062,
"updated_at": false,
"category": ""
},
{
"id": 20,
"creator": null,
"title": "Test artikel 3",
"content": "<p>Dit is een test. Geen sticky.</p>",
"tags": null,
"photo": "website/uploads/",
"sticky": 0,
"created_at": 1506345662,
"updated_at": false,
"category": ""
},
{
"id": 23,
"creator": null,
"title": "Hovenier 2",
"content": null,
"tags": null,
"photo": "website/uploads/1505990708_Verboon Hoveniers.jpg",
"sticky": 0,
"created_at": 1506432062,
"updated_at": false,
"category": "Test categorie 1"
}
]
}
As you can see, there is a created_at object in the array based on a unix timestamp. What I'm trying to do is sort these items based on that created_at object using angular 4 typescript.
I've tried the sort() function, but I can't seem to get it to work.
Can anyone tell what is the best way to tackle this problem? I think it must be something really simple, but I can't seem to get it.
Thanks!
edit: I have placed it in a variable, but I get this:
ERROR TypeError: Cannot read property 'sort' of undefined
also, this is the console.log from the variable.
Maybe this code can help you:
const {posts} = yourJSON;
posts.sort((a, b) => a.created_at - b.created_at);
Write the sort function like this.
var sortedPosts = data.post.sort((item1,item2) => item2.created_at - item1.created_at)
You need to do something like this.
yourObjectName.post.sort(function(a, b) {
return a.created_at - b.created_at;
});
Store your data in a variable, then sort the post property of your json object
var items = {your jsons}
items.post.sort((a,b) => a.created_at - b.created_at)
Related
Currently, this works and doesn't give my error while running but my text editor is giving me an error that says property 'categories' does not exist on type 'CategoryInterface[]' (on the line where response.categories is assigned to variable) so I'm not sure if I'm doing things right.
public categories: CategoryInterface[];
.subscribe((response: CategoryInterface[]) => {
this.categories = response.categories;
console.log(this.categories);
});
My backend returns this:
{
"categories": [
{
"categoryId": 1,
"name": "Important",
"description": "This category is important.",
"order": 1,
"createdBy": null,
"createdAt": "2017-11-25 12:09:04",
"updatedBy": null,
"updatedAt": "2018-01-17 23:53:25",
"categoryBoards": [
{
"categoryBoardId": 1,
"categoryId": 1,
"name": "Announcements",
"description": null,
"order": 2,
"createdBy": null,
"createdAt": "2017-11-25 12:09:49",
"updatedBy": null,
"updatedAt": "2018-01-18 00:09:02"
},
{
"categoryBoardId": 23,
"categoryId": 1,
"name": "Rules",
"description": null,
"order": 1,
"createdBy": null,
"createdAt": "2018-01-18 00:08:57",
"updatedBy": null,
"updatedAt": "2018-01-19 00:05:51"
}
]
}
]
}
You are trying to cast your api response to an array of CategoryInterface which is not the case, you better use your subscribe method like this:
.subscribe((response: any) => {
this.categories = <CategoryInterface[]> response.categories;
console.log(this.categories);
});
It's the your api response categories which needs to be casted to CategoryInterface[]
Bonus: The angular style-guide notice that you need to declare classes instead of interfaces and you don't have to suffix the class name with Interface, so just name your CategoryInterface to Category.
You get the error because you declare response as a CategoryInterface[], but response.categories is actually the CategoryInterface[]. response is just a wrapper around the array. All the types are stripped out when the typescript is converted to javascript, which is why it works fine at runtime.
I am trying to access the card json value, to no avail.
In my scenario, I am asking the bot about "weather in London" and it replies back with "It is currently 9 degrees celcius in London." via the webhook.
Which is correct and dynamic.
However, I am trying to also pass the values to a card too.
In the json reply, I do get the card as so
{
"id": "REMOVED",
"timestamp": "2017-12-05T11:10:52.033Z",
"lang": "en",
"result": {
"source": "agent",
"resolvedQuery": "weather in london",
"action": "sayWeather",
"actionIncomplete": false,
"parameters": {
"geo-city": "London"
},
"contexts": [],
"metadata": {
"intentId": "REMOVED",
"webhookUsed": "true",
"webhookForSlotFillingUsed": "false",
"webhookResponseTime": 626,
"intentName": "Weather"
},
"fulfillment": {
"speech": "It is currently 9 degrees celcius in London.",
"source": "agent",
"displayText": "It is currently 9 degrees celcius in London.",
"messages": [
{
"type": 0,
"speech": "It is currently 9 degrees celcius in London."
}
],
"data": {
"items": [
{
"simpleResponse": {
"textToSpeech": "This is the first simple response for a basic card"
}
},
{
"basicCard": {
"title": "Title: this is a title",
"formattedText": "This is a basic card. Text in a\n basic card can include \"quotes\" and most other unicode characters\n including emoji 📱. Basic cards also support some markdown\n formatting like *emphasis* or _italics_, **strong** or __bold__,\n and ***bold itallic*** or ___strong emphasis___ as well as other things\n like line \nbreaks",
"subtitle": "This is a subtitle",
"image": {
"url": "https://developers.google.com/actions/images/badges/XPM_BADGING_GoogleAssistant_VER.png",
"accessibilityText": "Image alternate text"
},
"buttons": [
{
"title": "This is a button",
"openUrlAction": {
"url": "https://assistant.google.com/"
}
}
]
}
},
{
"simpleResponse": {
"textToSpeech": "This is the 2nd simple response ",
"displayText": "This is the 2nd simple response"
}
}
]
}
},
"score": 1
},
"status": {
"code": 200,
"errorType": "success",
"webhookTimedOut": false
},
"sessionId": "REMOVED"
}
Accessing the value of speech using data.result.fulfillment.speech works fine.
However, when using data.result.fulfillment.data.items.basicCard.image.url it just doesnt work. And if I go up several levels, I do get:
[object Object]
Your help is appreciated.
The items attribute is a list and not an object. As such, you'll have to use a numerical index to retrive the data. In the example you provided the index of the basicCard object is second so your code should look something like this:
data.result.fulfillment.data.items[1].basicCard.image.url
Notice the [1] after items.
Bear in mind that if the order of this list changes you may no longer be retrieving a basicCard object so you may want to add some checking to make sure you're retrieving the data you want.
I have a SharePoint(SP) library with some custom columns.
One of the columns contains a lookup field pointing to a SP list.
I need to retreive the documents in the list and all the custom fields including the fields from the lookup list (join).
There are some Q&A on stackoverflow regarding this topc, but they are about SP lists not SP document libraries.
This is what I have come up with until now (using javascript to perform a GET):
{
"url": "sites/mysite/_api/Web/GetFolderByServerRelativeUrl('/sites/mysite/myfilelibrary')
/files?$select=Name,LinkingUrl,TimeCreated,TimeLastModified,Title,ListItemAllFields
&$expand=ListItemAllFields/myListIdId"
}
This results into:
{
"value": [
{
"ListItemAllFields": {
"FileSystemObjectType": 0,
"Id": 1,
"ServerRedirectedEmbedUrl": "https://mydomain.sharepoint.com/sites/mysite/_layouts/15/WopiFrame.aspx?sourcedoc={abababab-efff-4e69-94de-128ff7c14256}&action=interactivepreview",
"ContentTypeId": "0x010100769480B9F5404447A43367BFC5B86AAB",
"Title": null,
"checkResponsible": null,
>>>>>>>>>>>>"myListIdId": 15, <<<<<<<<<<<<<<<<<<<<<
"SharedWithUsersId": null,
"SharedWithDetails": null,
"ID": 1,
"Created": "2016-07-25T06:04:56",
"AuthorId": 9,
"Modified": "2016-07-26T15:11:27",
"EditorId": 11,
"OData__CopySource": null,
"CheckoutUserId": null,
"OData__UIVersionString": "9.0",
"GUID": "898770aa-da56-40ae-9db1-430bba2da9bd"
},
"LinkingUrl": "https://mydomain.sharepoint.com/sites/mysite/myFileLibrary/Document.docx?d=w3028f42eefff4e6994de128ff7cd6e48",
"Name": "Document.docx",
"TimeCreated": "2016-07-25T13:04:56Z",
"TimeLastModified": "2016-07-26T22:11:27Z",
"Title": ""
}
]
}
The field myListIdId is returned but not expanded.
$expand=ListItemAllFields/myListIdId
should do the trick, but clearly it does not.
What am I missing?
According to this article, you specify the expanded field in the select parameter.
Revised:
"...$select=Name,LinkingUrl,TimeCreated,TimeLastModified,Title,ListItemAllFields/myListIdId
&$expand=ListItemAllFields"
I've tried 100 different things, and spend days looking through Google and Stackoverflow, but I can't find a solution to this problem. Everything I call after the body of this API response returns undefined!
The response from Facebook SDK looks like this:
[
{
"body": "[
"data": [
{
"name": "Larry Syid Wright",
"administrator": false,
"id": "xxx"
}, {
"name": "Melissa Long Jackson",
"administrator": false,
"id": "xxx"
}, {
"name": "Charlotte Masson",
"administrator": false,
"id": "xxx"
}
],
"paging": {
"next": "url"
}
]"
},{
"body": "{
"data": [
{
"id": "xxx_xxx",
"message": "In honor of Halloween, how many of you have your own ghost stories? Who believes in ghosts and who doesn't?",
"type": "status",
"created_time": "2014-10-31T20:02:01+0000",
"updated_time": "2014-11-01T02:52:51+0000",
"likes": {
"data": [
{
"id": "xxx",
"name": "Joe HerBatman Owenby Jr."
}
],
}
"paging": {
"cursors":
{
"after": "xxx",
"before": "xxx"
}
}
}
},{
"id": "xxx_xxx",
"from": {
"id": "xxx",
"name": "Jessica Starling"
},
"message": "Watching the "Campaign" and I can't help but notice what a fantastic job they did (Will ferrell and all) with that North Carolina accent! Ya'll know we sound different than other southern states ;)",
"type": "status",
"created_time": "2014-11-01T02:36:21+0000",
"updated_time": "2014-11-01T02:36:21+0000",
"likes": {
"data": [
{
"id": "xxx",
"name": "Scott Williams"n
}
]
}
}
],
"paging": {
"previous": "xxx",
"next": "xxx"
}
}"
}
]
This response is from a batch call. If I call them separately, I can easily iterate through the responses, and get everything from them. When I call them in the batch though, I can't get past "body", and I need to use a batch call.
console.log(response[0].body); will return the object inside the body of the first part of the response, but console.log(response[0].body.data); returns undefined. I just don't get it. This should be simple but it's like there's a lock on the door and I don't have the right key.
I normally have no issue iterating through objects, so I don't need a generalized answer. I need help seeing whatever it is here that I don't see. Why does the console show undefined when I call anything after the body, and what do I need to be doing to get any of these values?
That JSON contains nested JSON. body seems to be a string. Use
var body = JSON.parse(response[0].body);
The values from the body are just strings.which are embedded as json.So firstly you would need to parse them using JSON.parse.
The code would be like
var body = JSON.parse(response[0].body);
I am having problem with my data.
My JSon looks like that:
[
{
"link": {
"created_at": "2013-10-07T13:31:43+09:00",
"id": 8,
"items_count": 4,
"key": "0iqVSnTU-BtJ1ItVKRe2VMWvRMU",
"mode": "standard",
"name": "sdasadads",
"pusher_key": "1jtsrzl3n6i1DKA3tSZJM6LPnfQ",
"readonly_key": "R_dD5oHMsruu0YzYVKEOA8hKKXA-r",
"updated_at": "2013-10-08T14:06:07+09:00",
"user_id": 2
}
},
{
"link": {
"created_at": "2013-10-07T13:32:56+09:00",
"id": 9,
"items_count": 1,
"key": "Mj-6Cc-_qaGlVTPgqKexzeijYNA",
"mode": "standard",
"name": "Untitled2",
"pusher_key": "hGE0D8TSar_H_Gv9MWdpj26gamM",
"readonly_key": "T53SNKPgyf7KvRUMzDQPaM99AAc-r",
"updated_at": "2013-10-07T13:33:14+09:00",
"user_id": 2
}
},
{
"link": {
"created_at": "2013-10-11T11:18:06+09:00",
"id": 10,
"items_count": 0,
"key": "X_ZoKxFPHtsvSU5W11gXx1653FU",
"mode": "standard",
"name": "Usdadasas",
"pusher_key": "0PZ860awofRKB9XIrXba-xY6u14",
"readonly_key": "2rzrRZAaR7UZRK3UbUId8xmFzd4-r",
"updated_at": "2013-10-11T11:18:06+09:00",
"user_id": 2
}
}
}
I am trying to print put all the names of the links like that:
$.post( "http://0.0.0.0:9292/api/links", function( data ) {
document.getElementById("test").innerHTML = data[link][0].name;
});
but it doesn't work.
How can I grub all the names and put it in html?
The objects are inside the array, not the other way around.
link is a literal property name, not a variable containing one as a string
Thus:
data[0]['link']['name']
You'll also need to make sure that the response has an application/json content type.
Grabbing all the names will require you to use a loop and change the 0 each time round it.
First of all change last "}" to "]" (your top structure is array not object )
Then try this
$.post( "http://0.0.0.0:9292/api/links", function( data ) {
document.getElementById("test").innerHTML = data[0].link.name;
});
Array.prototype.map() is a good way to fetch something from data structure. With your test data in data variable, could would look like this:
Example here.
<div class="names"></div>
var names = data.map(function (item) {
return item.link.name
});
document.querySelector(".names").innerHTML = names;