Reputation: 89
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
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
Reputation: 22490
You could with Array#reduce
and Array#map
Array#reduce
convert the array to object for easy to find. its better then using find
with in mapArray#map
update the new key of users
.it will carry the usernameconst 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
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>
);
});
})}
Upvotes: 1