I need help extracting specific JSON values based on user-selected input keys and converting them into QuestionBase<any>[]
. Currently, my code successfully extracts values for the key "test" only:
// dropdown HTML
<select class="form-control" name="test" id="test" (ngModel)="test" (change)="onSelectChange($event, test.form)">
<option selected disabled hidden style='display: none' value=''></option>
<option value="test">Test</option>
<option value="other">Other</option>
</select>
// question-list.component.ts
onSelectChange($event: any, form: NgForm) {
this.getQuestions();
}
getQuestions() {
this.questionService.getQuestions()
.subscribe(questions => this.questions = questions.sort((a, b) => a.order - b.order),
error => this.errorMessage = <any>error);
}
// question.service.ts
getQuestions(): Observable<QuestionBase<any>[]> {
return this.http.get(this.jsonUrl)
.map(this.extractTest)
.catch(this.handleError);
}
private extractTest(res: Response) {
let body = res.json();
return body["test"] || {};
}
// JSON
{
"test": [{
key: 'firstName',
label: 'First name',
value: 'Bombasto',
required: true,
order: 1
}, {
key: 'brave',
label: 'Bravery Rating',
options: [
{key: 'solid', value: 'Solid'},
{key: 'great', value: 'Great'},
{key: 'good', value: 'Good'},
{key: 'unproven', value: 'Unproven'}
],
order: 2
}],
"other": [{
key: 'emailAddress',
label: 'Email',
type: 'email',
order: 1
}]
}
I've attempted passing the selected value as an argument to getQuestions()
and extractTest
in order to return body[selected] || {}
in extractTest
, but it results in an undefined object in my subscribe function and triggers an error during sorting. I suspect my misunderstanding of how map or subscribe functions work might be causing the issue.
Any suggestions on how to tackle this problem would be greatly appreciated.