I am making an app in react-native and I am gathering my data via API. I am trying to add a new feature where information is organized by date. So the API sends data that looks like this:
{
"channel_count": "1",
"channels": [
{
"logo": "default.png",
"name": "Default Channel",
"token": "default"
}
],
"messages": [
{
"2022-07-04": [
{
"body": "Body",
"title": "Title"
},
]
},
{
"2022-07-01": [
{
"body": "Body",
"title": "Title"
}
]
}
]
}
I am able to 'get into' the messages in the JSON, but since I do not know which date, I can not go another layer deeper.
I want to display this data while organizing the messages by date. The issue is, how am I able to map the messages when I do not readily know what dates will be shown? This displays messages from a 7 day radius, but messages are not sent everyday, as shown in the JSON.
On a basic level, I want my app to look like this:
Date: 2022-07-04
Title: Title
Body: Body
Date: 2022-07-01
Title: Title
Body: Body
(and when the app is more complete with more data, the messages will still be organized by date)
CodePudding user response:
Did you heard about Object.entries
, Object.values
, Object.keys
and for in
and for of
loops?
const data = {
"channel_count": "1",
"channels": [
{
"logo": "default.png",
"name": "Default Channel",
"token": "default"
}
],
"messages": [
{
"2022-07-04": [
{
"body": "Body",
"title": "Title"
},
]
},
{
"2022-07-01": [
{
"body": "Body",
"title": "Title"
}
]
}
]
}
console.log(data.messages.flatMap(e => Object.entries(e)))
CodePudding user response:
As per your need, you can try below code it should work for you.
const data = {
"channel_count": "1",
"channels": [
{
"logo": "default.png",
"name": "Default Channel",
"token": "default"
}
],
"messages": [
{
"2022-07-04": [
{
"body": "Body",
"title": "Title"
},
]
},
{
"2022-07-01": [
{
"body": "Body",
"title": "Title"
}
]
}
]
}
const { messages } = data || {};
const mappedData = (messages || []).map(item => {
const [key] = Object.keys(item);
const [value] = item[key];
return { date: key, body: value.body, title: value.title};
});
console.log("updatedData", mappedData)
Now you have your data in array of object in the for of
[{ date: "2022-07-04", body: "Body", title: "Title" }, ....]
you can use map and render data on your UI.