tech_enthusiasist
tech_enthusiasist

Reputation: 89

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

I have two arrays like

 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>

I have getting output as

    22,23
    23

How to get an output like

   Peter,John
   John

Upvotes: 0

Views: 71

Answers (3)

ikhvjs
ikhvjs

Reputation: 5937

You can use find() to get the username from 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>);

Upvotes: 3

prasanth
prasanth

Reputation: 22490

You could with Array#reduce and Array#map

  1. Array#reduce convert the array to object for easy to find. its better then using find with in map
  2. Then Array#map update the new key of users.it will carry the username

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

Upvotes: 1

Shyam
Shyam

Reputation: 5497

 {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

Upvotes: 1

Related Questions