首页 > 解决方案 > 按 ID 映射对象数组并更新数组中的每个现有对象

问题描述

我正在尝试进行调用,返回一个对象数组,然后通过 id 遍历数组中的每个对象并进行额外的调用。通过第二次提取,我需要向原始数组中的每个对应对象添加一个新对象。请参阅下面的代码示例,并在此先感谢您!

脚步:

  1. 将搜索参数传递给 postSearchPromise
  2. 映射结果并存储所有 id 的数组
  3. 将每个 id 传递到 getMediaPromise(我已经定义了令牌)
  4. 将 getMediaPromise 中的每个响应对象添加到现有数组中的相应对象。
  5. 使用 reducer 存储最终结果(这是一个 React Native 应用程序,我在以下屏幕上使用 FlatList 指向此存储的数据,循环遍历数组并在屏幕上显示列表)
async function search() {
   const toSend = {
     title,
     age,
     location
   };

   try {

     const results = await postSearchPromise(token, toSend);
     const theUsers = await results.map(getUsers);

     function getUsers(item) {
       var users = item.id;
       return users;
     }

     const avatars = await getMediaPromise(token, theUsers);

     const mapped = await results.map(element => ({avatar: avatars ,...element}));

     dispatch({type: 'SEARCH_RESULTS', payload: mapped});

   } catch (e) {
     console.log("The Error:" , e);
   }

}

目前,这几乎可以工作,但“头像”从 getUsers 获取所有 id,并将它们以逗号分隔的列表一起发送,在“getMediaPromise”内一次 - 这不是意图,但我理解为什么代码是以这种方式行事。我不确定如何遍历每个 id 并将新对象添加到数组中的每个现有对象。

我开始的搜索结果:

[
 {
   id: "123",
   name: "John",
   location: "USA"
 },
 {
   id: "456",
   name: "Jane",
   location: "USA"
 },
 {
   id: "789",
   name: "Jerry",
   location: "USA"
 }
]

我需要完成的搜索结果:

[
 {
   id: "123",
   name: "John",
   location: "USA",
   avatar: {
     type: "default",
     status: "200",
     ok: true,
     url: "http://localhost:3000/media/123"
   }
 },
 {
   id: "456",
   name: "Jane",
   location: "USA",
   avatar: {
     type: "default",
     status: "200",
     ok: true,
     url: "http://localhost:3000/media/456"
   }
 },
 {
   id: "789",
   name: "Jerry",
   location: "USA",
   avatar: {
     type: "default",
     status: "200",
     ok: true,
     url: "http://localhost:3000/media/789"
   }
 }
]

我愿意采用一种完全不同的方式来执行此操作,但如上所述...我在以下屏幕上使用 FlatList,因此这是一个对象数组非常重要,因此我的 FlatList 可以轻松地循环存储数据并相应地拉出每一块。谢谢!

标签: javascriptarrays

解决方案


推荐阅读