Home > Net >  Creating a function that compares 2 different arrays and passs down each matching pair into a compon
Creating a function that compares 2 different arrays and passs down each matching pair into a compon

Time:07-30

I am trying to create a component that calls upon two arrays. The arrays are them mapped out and the pair that matches is send down through props into a child component. I am making a list component that calls said arrays from the back end and then sends down the information to a listItem component to be rendered. The arrays look something like this

const Stores = [
{
id: 1,
name: Store One,
},
{
id: 2,
name: Store Two,
},
]
const Users = [
{
id: 100,
name: User One,
storeId: 1,
},
{
id: 200,
name: User Two,
storeId: 1,
},
{
id: 300,
name: User Three,
storeId: 2,
},
{
id: 400,
name: User Four,
storeId: 2,
},
]

Currently i am just passing down the user information into the listItem component and using http requests on each item but as you can tell when the User or Stores list reaches 100 items that the amount of http requests will bog down the app too much. What I thought of is just calling once in the List component and passing down each information that way it would be one call but cannot figure out the function required to acheive this. Is there anyone that can help me brainstorm?

CodePudding user response:

const Stores = [{
    id: 1,
    name: 'Store One',
  },
  {
    id: 2,
    name: 'Store Two',
  },
]

const Users = [{
    id: 100,
    name: 'User One',
    storeId: 1,
  },
  {
    id: 200,
    name: 'User Two',
    storeId: 1,
  },
  {
    id: 300,
    name: 'User Three',
    storeId: 2,
  },
  {
    id: 400,
    name: 'User Four',
    storeId: 2,
  },
]

const grouped = Users.map(user => {
  // find store
  const store = Stores.find(store => store.id === user.storeId)
  // return grouped
  return {
    user: { ...user },
    store: { ...store }
  }
})

console.log(grouped)

  • Related