-2

I have an array of booking and types. From these two arrays I need to build an object. Everything works great, except for the types. Types return an array in each object (same). How can you return the correct object?

const booking = [{row: 1, num: 2, level:3}]
const types = [1,2,3,4,5]

export const selectResult = createSelector([selectBooking, selectTypes], (booking, types) => {
    return booking.map((book) => {
        return {
            row: book.row,
            num: book.num,
            levelId: book.level,
            discount: types
        }
    })
})
TeenDay
  • 54
  • 7
  • 2
    what **should** be the value of `discount`? you are setting it to `[1,2,3,4,5]` in your code - so your code is doing what you wrote – Bravo Mar 01 '22 at 04:22
  • @Bravo I'm saying that I don't know how to sort through the discounts and distribute them among the returned objects. I need to return not an array, but its elements – TeenDay Mar 01 '22 at 04:40
  • 1
    right, what's the logic of "sort through the discounts and distribute them among the returned objects" - you could `discount: types.pop()` - this will assign the last value and remove it from the array .... you could `discount: types[Math.floor(Math.random()*types.length)` to assign a random one, but that's not distributing as such ... – Bravo Mar 01 '22 at 04:41
  • @Bravo use pop in redux? It's a joke? the variables above are just an example of my store for clarity – TeenDay Mar 01 '22 at 04:58
  • Not a joke, not an answer either, but you need to describe the logic of **sort through the discounts and distribute them** before you get an answer - because **sort through the discounts and distribute them** means nothing to anyone but you – Bravo Mar 01 '22 at 05:02

2 Answers2

0

If you want to have an object of each booking with one type in it, you can use it like this

booking.map(book => {
    return types.map(type => ({
            row: book.row,
            num: book.num,
            levelId: book.level,
            discount: type
        }))
})

If you want to have discount values as an object instead of having an array, you can get it like this

booking.map((book) => {
        return {
            row: book.row,
            num: book.num,
            levelId: book.level,
            discount: {...types}
        }
    })
Himanshu
  • 71
  • 3
0

found a solution to my problem. It was enough to add indexes

export const selectResult = createSelector(
    [selectBooking, selectTypes, selectPrices],
    (booking, types) => {
        return booking.map((book, idx) => {
            return {
                row: book.row,
                num: book.num,
                levelId: book.level,
                type: types[idx]
            }
        })
    }
)
TeenDay
  • 54
  • 7