我们如何比较两个对象数组并显示两个数组中的项目

How can we compare two array of objects and display items from both array

我有两个数组,例如

 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

您可以使用 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>);

 {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

你可以 Array#reduceArray#map

  1. Array#reduce 将数组转换为对象以便于查找。 比在 map
  2. 中使用 find 更好
  3. 然后Array#map更新users的新密钥。它将携带用户名

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>)