如何构建对象 JS

how to build object JS

我有一系列预订和类型。我需要从这两个数组构建一个对象。一切都很好,除了类型。在每个对象中键入 return 数组(相同)。你怎么能 return 正确的对象?

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

如果你想要每个预订的对象都包含一种类型,你可以这样使用它

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

如果你想将折扣值作为对象而不是数组,你可以这样获取它

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

找到了解决我的问题的方法。添加索引就足够了

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