I have a concrete problem which I don’t know how to solve cleanly.
The variables are given, so with roomtypes, restriction, rules variables I have to generate a request.
const rateRequest = {rate: []}
const roomtypes = [100, 101]
const restriction = {
roomtypes: {
100: [201],
101: [201,202]
}
}
const rules = [
{
field: 'price',
value: 50
},
{
field: 'release',
value: 3
}
]
roomtypes.forEach((roomtype) =>
rateRequest.rate.push(
...restriction.roomtypes[roomtype].map((rateplanId) => ({
roomtypeId: roomtype,
rateplanId: rateplanId,
...rules.map((rule) => ({
[rule.field]: rule.value,
}))
}))
)
)
console.log(rateRequest)
Produces this output:
{
rate: [
{
'0': { price: 50 },
'1': { release: 3 },
roomtypeId: 100,
rateplanId: 201
},
{
'0': { price: 50 },
'1': { release: 3 },
roomtypeId: 101,
rateplanId: 201
},
{
'0': { price: 50 },
'1': { release: 3 },
roomtypeId: 101,
rateplanId: 202
}
]
}
But I want this ouput:
{
rate: [
{
price: 50,
release: 3,
roomtypeId: 100,
rateplanId: 201
},
{
price: 50,
release: 3,
roomtypeId: 101,
rateplanId: 201
},
{
price: 50,
release: 3,
roomtypeId: 101,
rateplanId: 202
}
]
}
How can I remove this indexes? Cannot be possible to achieve with map inside another map?
>Solution :
You should spread a plain object, not an array. You can use Object.fromEntries for this.
Not your question, but you can replace the outer forEach with a flatMap and so produce the rate array in a more functional programming way (without push). And for the inner object literal you can use some shorter syntax if you name your variables right:
const roomtypes = [100, 101];
const restriction = {roomtypes: {100: [201],101: [201,202]}};
const rules = [{field: 'price',value: 50},{field: 'release',value: 3}];
const rateRequest = {
rate: roomtypes.flatMap((roomtypeId) =>
restriction.roomtypes[roomtypeId].map((rateplanId) => ({
roomtypeId,
rateplanId,
...Object.fromEntries(rules.map(({field, value}) =>
[field, value]
))
}))
)
};
console.log(rateRequest);