I am trying from a post request with info to sort them "automatically".
- Each category is defined by a number (0 -> 1 -> ....)
- There is for each category 1 title defined by its number ex: "0": "Are planes flying?"
- 5 questions that go from A to E that contain the value q in its name ex: "0-qA": "maybe"
- And answers for each category ex: "0-A": "on" but if 0-B has not been checked then there will be nothing.
This is what come out of req.body:
{
'0': 'Are planes flying ?',
'1': 'Are tomatoes flying ?',
title: 'What flies',
'0-qA': 'Maybe,
'0-A': 'on'
'0-qB': 'Yes',
'0-qC': 'No',
'0-C': 'on',
'0-qD': 'Ask to Patrick',
'0-D': 'on',
'0-qE': 'Answer C',
'1-qA': 'Maybe no',
'1-qB': 'Yes',
'1-qC': 'No',
'1-C': 'on',
'1-qD': 'Do not ask me',
'1-D': 'on',
'1-qE': 'Answer A',
'1-E': 'on'
'num': '1' //equal to how many questions I have
}
then i want to "sort" them to look like this:
{
"title": "What flies",
"questions": [
{
"question": "Are planes flying ?",
"choix": [
{
"id": "A",
"text": "Maybe"
},
{
"id": "B",
"text": "Yes"
},
{
"id": "C",
"text": "No"
},
{
"id": "D",
"text": "Ask to patrick"
},
{
"id": "E",
"text": "Answer C"
}
],
"answers": [
"0-A",
"0-C",
"0-D"
]
},
{
"question": "Are tomatoes flying ?",
"choix": [
{
"id": "A",
"text": "Maybe no"
},
{
"id": "B",
"text": "Yes"
},
{
"id": "C",
"text": "No"
},
{
"id": "D",
"text": "Don't ask me"
},
{
"id": "E",
"text": "Answer A"
}
],
"answers": [
"1-C",
"1-D",
"1-E"
]
},
]
}
I've tried by using num with for(i in num)
but it came to nothing.
Thank you in advance for any answers you can bring me !
CodePudding user response:
You can iterate over the keys of the data, looping over values from 0
to data['num']
and matching choices and answers based on the patterns of the keys (choices starting with a number then -q
and answers with a number followed by -
and a letter which is not q
:
const data = {
'0': 'Are planes flying ?',
'1': 'Are tomatoes flying ?',
'title': 'What flies',
'0-qA': 'Maybe',
'0-A': 'on',
'0-qB': 'Yes',
'0-qC': 'No',
'0-C': 'on',
'0-qD': 'Ask to Patrick',
'0-D': 'on',
'0-qE': 'Answer C',
'1-qA': 'Maybe no',
'1-qB': 'Yes',
'1-qC': 'No',
'1-C': 'on',
'1-qD': 'Do not ask me',
'1-D': 'on',
'1-qE': 'Answer A',
'1-E': 'on',
'num': '1' //equal to how many questions I have
};
let result = {
'title': data['title'],
'questions': []
};
for (let i = 0; i <= parseInt(data['num']); i ) {
let key = i '';
let question = {
'question': data[key],
'choix': Object.keys(data)
.filter(k => k.startsWith(`${key}-q`))
.map(k => ({
id: k.split('q')[1],
text: data[k]
})),
'answers': Object.keys(data)
.filter(k => k.match(new RegExp(`${key}-[^q]\$`)))
};
result['questions'].push(question);
}
console.log(result)