I have an array of objects that looks like this:
[
{
type: 'car',
choices: [
'audi',
'honda',
'bmw',
'ford'
],
},
{
type: 'drink',
choices: [
'soda',
'water',
'tea',
'coffee'
],
},
{
type: 'food',
choices: [
'chips',
'pizza',
'cookie',
'pasta'
],
}
]
Using lodash how to transform it into something that looks like this:
[
{
question: [
{
drink: "tea"
},
{
car: "bmw"
}
]
},
{
question: [
{
food: "cookie"
},
{
car: "ford"
}
]
},
{
question: [
{
drink: "soda"
},
{
food: "pizza"
}
]
},
{
question: [
{
food: "chips"
},
{
drink: "water"
}
]
},
{
question: [
{
car: "audi"
},
{
food: "pasta"
}
]
},
{
question: [
{
car: "honda"
},
{
drink: "coffee"
}
]
},
]
The logic is as follow:
- Every question has a combination of 2 choices where every choice is of different type example (car and food).
- Combination of different types should occur only twice (car, food).
- No duplication of choices.
- The selection of choices should be randomized.
I tried to Flatten the array using this function
let flattenItems = _.flatMap(items, ({ type, choices}) =>
_.map(choices, choice => ({
question: [
{ type: type, choice: choice },
{ type: type, choice: choice }
],
})
));
but it's not what I need, and it's not random. I not sure my approach is the correct one, I'm thinking I should use a filter or reduce
Any help on how to solve this would be appreciated using JS or lodash would be good.
{ [obj1[randomObj].type] : obj1[randomObj].choices[randomChoice] }and you are picking pairs of two types with an associated random answer. Sorry, for some reason I misread it initially as you only wanting combinations of pairs of random types. I got it now.1-2then2-3then3-4then4-1then again1-2up to so on. In this case there will no combination from2-4. Do you want that or you want completely random..