Javascript 我如何遍历这个twitterapi消息列表?

Javascript 我如何遍历这个twitterapi消息列表?,javascript,arrays,api,loops,twitter,Javascript,Arrays,Api,Loops,Twitter,我目前正在使用Twitter API,特别是端点 端点返回的是消息对象数组 消息对象看起来是这样的 { target: { recipient_id: '0002' }, sender_id: '0001', source_app_id: '00000', message_data: { text: 'hello', entities: { hashtags: [], symbols: [], user_mentions: [], urls: [] } } }

我目前正在使用Twitter API,特别是端点

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

消息对象看起来是这样的

{
  target: { recipient_id: '0002' },
  sender_id: '0001',
  source_app_id: '00000',
  message_data: {
    text: 'hello',
    entities: { hashtags: [], symbols: [], user_mentions: [], urls: [] }
  }
}
基于此,如果我有这些对象的数组,那么我将使用for循环将具有相同发件人id或收件人id的邮件分组到对话数组中,同时跟踪哪些发件人id/收件人id已经分组,这样我就不会与相同的用户进行克隆对话

我目前拥有的是一个双for循环,其中第一个for循环获取一对发送者/接收者的id,第二个for循环检查任何其他具有匹配id的消息对象,并将其分组到一个数组中

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

编辑:(更多信息) 这就是我目前拥有的

 // Create conversations array
 convArr = [];

// see what the messages are
for (let i = 0; i < response.data.events.length; i++) {
   // if the next message has same recipient then skip
   sender_id = response.data.events[i].message_create.sender_id;
   recipient_id = 
      response.data.events[i].message_create.target.recipient_id;
   conversation = [];

   // Look for a certain matching sender and recipient id that matches original message
   for (let j = i; j < response.data.events.length; j++) {
      matchedSender = response.data.events[j].message_create.sender_id;
      matchedRecipient = 
      response.data.events[j].message_create.target.recipient_id;
      if((sender_id === matchedSender) | (sender_id === matchedRecipient) 
      &&
      (recipient_id === matchedSender) | (recipient_id === 
  matchedRecipient)) 
      {
     conversation.push(response.data.events[j]);
     } 
    }
   }
  convArr.push(conversation);
}
//创建对话数组
convArr=[];
//看看这些信息是什么
for(设i=0;i
根据您提供的信息,我认为这可以通过一个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(message.sender_id);
  let receiver = Number(message.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(message);
  }
  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] = [message];
  }

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

}, {}));
只要发送者id和接收者id是数字,就应该可以工作

编辑

下面是一些可能不清楚的简单解释

此函数的操作将根据您提供给它的参数而有所不同。但主要是,您将看到它用于从对象(即
{}
)提取值数组,而不是字符串或数组,因为它们有自己的方法来实现这一点

当谈到对象的值时,我指的是键/值对的值部分。例如:

let obj = {
  a: 1 // 'a' is the key, 1 is the value
  b: 2 // 'b' is the key, 2 is the value
};

let arrayOfValues = Object.values(obj); // Will return [1, 2]

array reduce函数是JavaScipt编程库中非常强大的工具。它接受一个函数作为参数,还可以选择一个累加器的初始值。它有点像一个有状态的forEach,它在数组中的每个项上运行一个函数,但在所有迭代中保持一个状态(累加器)

这是一个简单的减速器

let initialState = 'abc';
let values = ['d', 'e', 'f']

let result = values.reduce((acc, val) => {
  return acc + val;
}, initialState);

console.log(result) // 'abcdef';
..和一个简单的
forEach
循环的相同功能

let initialState = 'abc';
let values = ['d', 'e', 'f'];
let result = intialState;

values.forEach(value => {
  result += value;
});

console.log(result) // 'abcdef';
唯一的区别是,循环中使用的“状态”数据包含在
reduce
函数中并从该函数返回,与所有其他循环一样,您需要从循环本身之外的范围管理状态

三元运算符或类似的东西存在于各种语言中。它基本上是编写if-else语句的一种快速方法,其目的是确定单个变量的值。运算符的
部分后面的表达式类似于
if
,而
部分后面的表达式类似于else

这是一个简单的三元函数

let twenty = 20;
let isTwentyGreaterThanTen = twenty > 10 ? 'Yes' : 'No';

console.log(isTwentyGreayerThanTen); // 'Yes'
if/else
语句相同的功能

let twenty = 20;
let isTwentyGreaterThanTen;

if (twenty > 10) {
  isTwentyGreaterThanTen = 'Yes';
}
else {
  isTwentyGreaterThanTen = 'No';
}

console.log(isTwentyGreayerThanTen); // 'Yes'

您能提供示例数据(比您提供的更多)、预期输出和代码尝试吗?我刚刚看到了这一点。这看起来棒极了,我会试试的,谢谢。效果很好。我还不完全习惯这样做,所以我将对它进行剖析,找出它到底为什么有效,但你的评论确实有帮助。感谢您抽出时间为我解决这个问题。