根据索引向对象列表中的现有对象添加值



我的问题背景:首先,我有一个对象数组,每个对象包含一个名为entries的用户id。我必须使用每个对象中的id进行api调用,以获得包含其fullName的用户完整配置文件。我能够映射api调用的结果,以获得具有匹配id的所有用户的列表到我开始的初始列表,并且我还提取了他们的fullName(此变量标记为matches)。所以现在我有了userID的entries的初始列表[数组],以及我在api调用matches中发现的列表中所有ID匹配的数组列表,这个数组列表包含ID和名称。

我现在要做的是映射到entriesmatches来比较userID,如果找到匹配,那么我想将匹配内部的名称插入到entry中,该匹配是基于索引找到的。然而,我不确定如何正确地插入一个键值对和基于索引的对象内部,或者如果我接近这个正确的方式。下面是我的代码:

useEffect(() => {
const loadAllProviders = async () => {
//TODO: Make conditional if entries exists
try {
//get all providers
const results = await api.Providers.listnoAudit({ scope: "all" });
const allProviders = results.items;
//map over the entries to get providerId's out
const providerIDs = entries.map((entry) => entry.createdBy);
//map over response to get out provider names and id's
const idName = allProviders.map((provider) => [provider.id, provider.fullName]);
//find if any returned providers have matching ids to the ones in entries
const matches = idName.filter((match) => providerIDs.includes(match[0]));
//TODO: map over entries
// if matches[0] = entries.createdby then
//push matches[1] (name) into the object at the index where match occurs
entries.map((entry, idx) => {
matches.map((provider) => {
if (entry.createdBy === provider[0]) {

let en = {...entry, fullName: provider[1]}
}
})
});
} catch (err) {}
};
loadAllProviders();
}, [entries]);

在我的if语句中,你会看到我尝试使用扩展操作符将fullName添加到条目中,但我不确定如何实际用新对象替换旧对象。当我console out时,我得到的是已修改的项目……我对编码很陌生,任何建议都会很有帮助。

您可能可以reduce您的allProviders列表来获得您想要的。请看下面的例子:

let allProviders = [
{id: 1, name: "Amy"}, 
{id: 2, name: "Kamala"}, 
{id: 3, name: "Stacy"}, 
{id: 4, name: "Sunil"}
]
let entries = [{createdBy: 2}, {createdBy: 4}]
let providerIds = entries.map(e => e.createdBy)
let result = allProviders.reduce((matches, provider) => {
if(providerIds.includes(provider.id)) {
matches.push({ ...provider, createdBy: provider.id})
}
return matches;
},[])
console.dir(result)

最新更新