[英]Adding a value into an existing object in a list of objects based on the index
我的问题的背景:首先,我有一个对象数组,每个对象都包含一个名为entries
的用户 ID。 我必须使用每个 object 中的 ID 进行 api 调用,以获取包含其 fullName 的用户完整配置文件。 我能够对 api 调用的结果进行 map 以获取所有用户的列表,这些用户的 id 与我开始使用的初始列表匹配,并且我还提取了他们的 fullName 这个变量被标记为matches
。 所以现在我有了 userID entries
的初始列表 [array] ,以及我在 api 调用中找到的所有 ID matches
的 arrays 的列表,该列表与 ZA3CBC3F9D0CE2F2C1554E1B 和 IDC 671 的列表匹配。
我现在要做的是 map 对entries
和matches
项进行比较以比较用户 ID,如果找到匹配项,那么我想将匹配项中的名称插入到基于索引找到匹配项的entry
中。 但是,我不确定如何根据索引在 object 中正确插入键值对,或者我是否以正确的方式接近这一点。 这是我的代码:
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 添加到条目中,但我不确定如何用新的 object 实际替换旧的 object。 当我安慰 en 时,我得到了已修改的项目......我对编码很陌生,任何建议都会有所帮助。
你可能可以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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.