【问题标题】:How can we compare two array of objects and display items from both array我们如何比较两个对象数组并显示两个数组中的项目
【发布时间】:2021-06-08 13:46:09
【问题描述】:

我有两个类似的数组

 const arr1=[{id:0,name:'aa', 
  userId:'22,23'}, 
  
 {id:1,name:'bb',userId:'23'}]
 const arr2= 
 [{id:22,username:'Peter'},
  {id:23,username:'John'}]

 arr1.map((val,k)=><div>
     <p>val.userId</p>
 </div>

我得到了输出

    22,23
    23

如何获得类似的输出

   Peter,John
   John

【问题讨论】:

  • 要在 arr2 中显示在 arr1 中具有相同 id 的名称吗?
  • 是的,来自 arr1 的相同 userId。

标签: javascript arrays reactjs compare lodash


【解决方案1】:

你可以使用find()从arr2获取用户名

const arr1 = [
  { id: 0, name: "aa", userId: "22,23" },
  { id: 1, name: "bb", userId: "23" },
];
const arr2 = [
  { id: 22, username: "Peter" },
  { id: 23, username: "John" },
];

const output = arr1.map(o =>
  o.userId
    .split(",")
    .map(x => arr2.find(k => k.id === Number(x)).username)
    .join(",")
);

output.map((val)=> <div><p>val</p></div>);

【讨论】:

    【解决方案2】:
     {arr1.map((val, k) => {
            const ids = val.userId.split(",");
            return ids.map((id) => {
              const user = arr2.find((user) => user.id === Number(id));
              return (
                <div key={`${val.id}-${user.id}`}>
                  <p>{user.username}</p>
                </div>
              );
            });
          })}
    

    Working Sandbox

    【讨论】:

      【解决方案3】:

      您可以使用 Array#reduceArray#map

      1. Array#reduce 将数组转换为对象以便于查找。 最好在地图中使用find
      2. 然后Array#map更新users的新key,会携带用户名

      const arr1=[{id:0,name:'aa', userId:'22,23'},{id:1,name:'bb',userId:'23'}] 
      const arr2= [{id:22,username:'Peter'}, {id:23,username:'John'}]
      
      const obj = arr2.reduce((acc,{id,username})=>(acc[id]=username,acc),{})
      
      const res = arr1.map(({userId,...a})=>{
          const users = userId.split(',').map(id=> obj[id]).join(',')
          return ({...a,userId,users})
      })
      
      console.log(res)
      res.map((val,k)=><div>
           <p>val.users</p>
       </div>)
      

      【讨论】:

        猜你喜欢
        • 2017-07-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-07
        • 1970-01-01
        相关资源
        最近更新 更多