【问题标题】:Adding a value into an existing object in a list of objects based on the index根据索引将值添加到对象列表中的现有对象中
【发布时间】:2021-05-31 00:45:27
【问题描述】:

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

我现在要做的是在entriesmatches 上映射以比较用户ID,如果找到匹配项,那么我想将匹配项中的名称插入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 添加到条目中,但我不确定如何用新对象实际替换旧对象。当我安慰我时,我得到了已修改的项目......我对编码很陌生,任何建议都会有所帮助。

【问题讨论】:

    标签: javascript arrays reactjs object array.prototype.map


    【解决方案1】:

    您可能可以通过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)

    【讨论】:

      猜你喜欢
      • 2021-10-24
      • 1970-01-01
      • 2021-10-16
      • 1970-01-01
      • 2022-01-20
      • 2014-03-26
      • 1970-01-01
      • 2022-06-29
      • 1970-01-01
      相关资源
      最近更新 更多