Answer the question
In order to leave comments, you need to log in
How to add a block if it doesn't exist?
Good afternoon!
There is json in this format
{
"dialog": [
{
"date": "16-04-2020",
"time": "10:35",
"text": "Текст сообщения 3"
},
{
"date": "16-04-2020",
"time": "09:16",
"text": "Текст сообщения 2"
},
{
"date": "15-04-2020",
"time": "18:59",
"text": "Текст сообщения 1"
}
]
}
$.ajax({
url: 'chat.php',
type: "GET",
dataType: "json",
success: function(json) {
if (typeof(json.dialog) == 'object') {
$('div.dialog').append(json.dialog.map(function(n) {
return '<div><span name="text">' + n.text + '</span><span name="time">' + n.time + '</span></div>';
}).join(''));
}
}
});
<div class="dialog">
<div>16-04-2020</div>
<div><span name="text">Текст сообщения 3</span><span name="time">10:35</span></div>
<div><span name="text">Текст сообщения 2</span><span name="time">09:16</span></div>
<div>15-04-2020</div>
<div><span name="text">Текст сообщения 1</span><span name="time">18:59</span></div>
</div>
<div>%date%</div>
Answer the question
In order to leave comments, you need to log in
if (typeof(json.dialog) == 'object') {
const _dialog = json.dialog.reduce((acc,cur,i,a)=>{
const index = acc.findIndex(item => item.date === cur.date)
if( index !== -1 ){
acc[index].message.push({text: cur.text, time: cur.time})
}else{
cur.message = []
cur.message.push({text: cur.text, time: cur.time})
acc.push(cur)
}
return acc
},[])
$('div.dialog').html(_dialog.map(item => {
let div = `<div>${item.date}</div>`
item.message.forEach(_item => {
div += `<div><span name="text">${_item.text}</span><span name="time">${_item.time}</span></div>`
})
return div;
}).join(''));
}
1. Upon shipment of json, it is worth passing it to another function.
2. Which will receive the data and process it, ideally sort by date.
3. Even easier - to form an array of objects, where it will be:
[
{
date: ...
messages: [...]
},
]
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question