After pulling data from a database in JSON format and assigning it to the variable 'var tabs', here is how the formatted JSON looks:
[{
"TAB_ID": "1",
"TAB_NAME": "TAB ONE",
"TAB_DISPLAY": "1",
"QUESTIONS": [{
"QUESTION_ID": 1,
"QUESTION": "Question number one",
"ANSWER": ""
}, {
"QUESTION_ID": 2,
"QUESTION": "Question number two",
"ANSWER": ""
}, {
"QUESTION_ID": 3,
"QUESTION": "Question number six",
"ANSWER": ""
}]
}, {
"TAB_ID": "1",
"TAB_NAME": "TAB ONE",
"TAB_DISPLAY": "1",
"QUESTIONS": [{
"QUESTION_ID": 1,
"QUESTION": "Question number one",
"ANSWER": "Some Other Answer"
}, {
"QUESTION_ID": 2,
"QUESTION": "Question number two",
"ANSWER": ""
}, {
"QUESTION_ID": 3,
"QUESTION": "Question number six",
"ANSWER": "Some Still Different Answer"
}]
}]
I am now tasked with iterating over this array and implementing the following logic:
For each QUESTION within the TAB, if the QUESTION has an ANSWER, I should append a key/value pair of "HAS_ANSWER": "1" to that QUESTION.
{
"QUESTION_ID": 1,
"QUESTION": "Question number one",
"ANSWER": "Some Other Answer",
"HAS_ANSWER": "1"
}
Despite extensive research on Underscore documentation and numerous examples, I can't seem to figure out how to approach this task efficiently.
My current understanding suggests leveraging nested _.map functions, but all examples I've encountered yield a subset of objects rather than the desired modification and extension within the existing JSON structure (array of objects).
Any assistance or guidance in tackling this challenge would be immensely appreciated.
Update:
By employing the snippet below:
data = _.map(data, obj => _.map(obj.QUESTIONS, q => {
if (q.ANSWER) {
q.HAS_ANSWER = 1;
}
return q;
}));
The script successfully iterates over the questions, making necessary modifications. However, it only returns an array of questions without retaining the original outer-layer TAB data:
"TAB_ID": "1",
"TAB_NAME": "TAB ONE",
"TAB_DISPLAY": "1",
To resolve this, utilizing _.each for the outer array and _.map for the inner array is recommended:
data = _.each(data, obj => _.map(obj.QUESTIONS, q => {
if (q.ANSWER) {
q.HAS_ANSWER = 1;
}
return q;
}));
Note: The => syntax is only compatible with newer JavaScript implementations and not supported in Safari/Webkit browsers. Therefore, use the alternative syntax below for better cross-browser compatibility:
data = _.each(data, function(obj){
_.map(obj.QUESTIONS, function(q){
if (q.ANSWER) {
q.HAS_ANSWER = 1;
}
return q;
});
});
This modified approach aligns perfectly with the required outcome.