V
V
venaf342282020-04-16 17:15:35
JavaScript
venaf34228, 2020-04-16 17:15:35

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(''));
        }
    }
});

How to display blocks in this format:
<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>

those. it is necessary to display the block with the date And then display all the records related to this date, and so on.
<div>%date%</div>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
Just Me, 2020-04-16
@venaf34228

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(''));

}

A
Arseny, 2020-04-16
Matytsyn @ArsenyMatytsyn

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: [...]
  },
]

Such an object is simply stupidly easier to deduce into a template.
4. Next, display all this crap according to the conditions: date + messages in which this date matches.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question