Home > Blockchain >  How to correctly check relations inside arrays of objects?
How to correctly check relations inside arrays of objects?

Time:10-17

I have two array of objects. In one I have data on items and its characteristics, and in the other I have list of categories with the id key. Both are fetching from an external API so I can't modify them manually.

first array of object:

[{
title: "xxx",
desc: "zzz",
genre_ids: [1, 2, 3]}

second array of object:

[{id: 1,
name: "women"}]

I want to display name's of the gander using second array. I had two failed attempts:

first approach

{listCategory.map(z => {z.id.includes(item.genre_ids)
    return (z.name)} ) }

second approach

{listCategory.filter(cat => 
     cat.id === item.genre_ids
).map(categ => {
    console.log("categ",  categ.name)
    return(<p key={uuid()}>{categ}</p>)})}

CodePudding user response:

You can create another array that would be a Map of the first array where you are retrieving the second array data using a find

const firstArr = [{
  title: "xxx",
  desc: "zzz",
  genre_ids: [1, 2, 3]
}]

const secondArr = [
  {id: 1,name: "women"},
  {id: 2,name: "men"},
  {id: 3,name: "other"},
]

const arrWithAllInformations = firstArr.map(item => {
  const { title, desc, genre_ids} = item
  const genres_full = genre_ids.map(id => secondArr.find(genre => genre.id === id))
  return {
    title,
    desc,
    genres: genres_full
  }
})

console.log(arrWithAllInformations)

You can then loop through the arrWithAllInformations objects and display the informations as you want.


More consise way :

const firstArr = [
  {title: "xxx",desc: "zzz",genre_ids: [1, 2, 3]}
]

const secondArr = [
  {id: 1,name: "women"},
  {id: 2,name: "men"},
  {id: 3,name: "other"},
]

const arrWithAllInformations = firstArr.map(item => ({...item, genres: item.genre_ids.map(id => secondArr.find(genre => genre.id === id))}))

console.log(arrWithAllInformations)

CodePudding user response:

You can use flatMap and a Set to remove duplicates.

const first = [{
  title: "xxx",
  desc: "zzz",
  genre_ids: [1, 2, 3]
}, {
  title: "xxx",
  desc: "zzz",
  genre_ids: [1, 2, 4]
}];

const second = [{
  id: 1,
  name: "women"
}, {
  id: 2,
  name: "man"
}, {
  id: 7,
  name: "non-binary"
}];

const ids = new Set(first.flatMap(({
  genre_ids
}) => genre_ids));
const filtered = second.flatMap(({
  id,
  name
}) => ids.has(id) ? name : []);
console.log(filtered);

  • Related