我如何遍历此Twitter api消息列表?

问题描述 投票:0回答:1

我当前正在使用Twitter API,特别是https://api.twitter.com/1.1/direct_messages/events/list.json端点。

端点返回的是消息对象数组。

消息对象看起来像这样

{
  target: { recipient_id: '0002' },
  sender_id: '0001',
  source_app_id: '00000',
  message_data: {
    text: 'hello',
    entities: { hashtags: [], symbols: [], user_mentions: [], urls: [] }
  }
}

基于,如果我有这些对象的数组,那么我将使用for循环将具有相同sender_id或receive_id的消息分组到一个对话数组中,同时还要跟踪已对哪些sender_id / recipient_id进行了分组,因此我没有克隆与相同用户的对话。

我目前拥有的是一个双for循环,其中第一个for循环捕获一对sender / recipient_id,第二个for循环检查是否将其他具有匹配ID的其他消息对象分组到一个数组中。

我似乎无法做的是跟踪已将哪对ID分组。我倾向于使用第三个for循环,但是我觉得有一个更简单的解决方案。

javascript arrays api loops twitter
1个回答
0
投票

根据您提供的信息,我认为可以使用单个reduce函数来完成。它们的关键是创建一个对象,该对象的键首先代表唯一的对话,然后再将其输出为数组。

类似这样的东西:

let messages = [ ... ] // Your messages inside here

// We want to run a reducer on the messages array to get
// unique conversations, then user Object.values to transform
// this back into an array.
let output = Object.values(messages.reduce((acc, message) => {

  // Convert both the sender and receiver ids to numbers.
  let sender = Number(val.sender_id);
  let receiver = Number(val.target.recipient_id);

  // We always want the conversation ID to be the same, regardless
  // of who the sender or receiver was, as long as it's the same
  // participants. The code below will always generate a string with
  // the smaller ID first, and the larger ID second, regardless of 
  // what role the users played in the message.
  let conversation_id = sender > receiver 
    ? `${receiver}_${sender}`
    : `${sender}_${receiver}`;

  if (acc[conversation_id]) {
    // If the conversation already exists, then we will just add this message
    // to the array of messages that make up the conversation
    acc[conversation_id].push(val);
  }
  else {
    // If the conversation doesn't exist, create a new array of messages
    // with this conversation ID and the first message initializing the array.
    acc[conversation_id] = [val];
  }

  // Return the updated accumulator, which will be used in the next
  // iteration.
  return acc;

}, {}));

只要sender_id和receiver_id是数字,就可以使用。

© www.soinside.com 2019 - 2024. All rights reserved.