javascript - 按 ID 映射对象数组并更新数组中的每个现有对象
问题描述
我正在尝试进行调用,返回一个对象数组,然后通过 id 遍历数组中的每个对象并进行额外的调用。通过第二次提取,我需要向原始数组中的每个对应对象添加一个新对象。请参阅下面的代码示例,并在此先感谢您!
脚步:
- 将搜索参数传递给 postSearchPromise
- 映射结果并存储所有 id 的数组
- 将每个 id 传递到 getMediaPromise(我已经定义了令牌)
- 将 getMediaPromise 中的每个响应对象添加到现有数组中的相应对象。
- 使用 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 可以轻松地循环存储数据并相应地拉出每一块。谢谢!
解决方案
推荐阅读
- node.js - Azure AD 使用 Passport.js 对访问令牌进行无效签名
- css - 如何使用 ::ng-deep 访问 Angular 子组件的 CSS
- c++ - 在线程之间协调哪些线程是空闲的最有效的方法是什么?
- javascript - 制作一个字典数组,字典的值也是一个数组
- java - Camunda bpm - 如何添加多个管理员用户?
- c# - Code-First 数据库和 PostgreSql 的问题
- python - 如何从异步信号处理程序中捕获自定义异常?
- java - Java nativeQuery:带有 AliasToEntityMapResultTransformer 的 ResultSet 在地图中具有无序列
- python - Colour according to custom values in Matplotlib
- python - 将列表中的每第四个项目保存到python字典中的一个键