Json和分组解决方案

时间:2015-01-14 10:27:35

标签: javascript jquery json

我试图选择收件箱的最后一条消息,并通过topic_id将它们分组到一个列表中。我想显示每个主题的最后一条消息。

数组看起来像这样:

[{
"id":"5",
"topic_id":"4",
"message_from":"24",
"message":"how do you do?",
"date":"2015-01-13 15:34:59"
},
{
"id":"6",
"topic_id":"1",
"message_from":"33",
"message":"go go go!!",
"date":"2015-01-13 13:35:06"
},
{
"id":"7",
"topic_id":"4",
"message_from":"33",
"message":"Je suis charlie",
"date":"2015-01-14 16:24:46"
},....

有没有循环的解决方案?

1 个答案:

答案 0 :(得分:1)

您无法在没有循环的情况下执行此操作,但您可以通过将事件序列分解为更小的函数来简化此操作。你可能不喜欢这种方法,但它是最干净的imo。或者,您可以使用第三方库(可能是下划线?),它允许您对数据进行分组。

基本上,获取所有记录的所有topic_id的列表,遍历该topic_id数组并拉出每个记录的最后一条记录并将其添加到输出数组。

// Get a list of all the topic ids - no duplicates
function getTopicIds(arr) {
  var out = [];
  arr.forEach(function (el) {
    if (out.indexOf(el.topic_id) === -1) out.push(el.topic_id);
  });
  return out;
}

// Given a topic_id, filter the array for only those records
// sort in desc order by id, and return the first record.
// Given that each record has a unique id, and we know that older
// messages will have higher ids, it's easier to sort by id than
// date here 
function getLastMsg(id, arr) {
  return arr.filter(function (el) {
    return el.topic_id === id;
  }).sort(function (a, b) { return +b.id - +a.id; })[0];
}

// return a array of the last messages for each topic_id
// in the records array
function getLastMsgs(arr) {
  return getTopicIds(arr).map(function (id) {
    return getLastMsg(id, arr);
  });
}

var result = getLastMsgs(arr);

DEMO