I am trying to get a nested structure from a MySQL query, and as a result of using JSON_OBJECT, one section of my return data is stringified. The data I am currently getting looks as follows:
[
{
"id": 3,
"body": "Does this product run big or small?",
"date_written": 1608535907,
"asker_name": "jbilas",
"helpful": 8,
"reported": 0,
"answers": null
},
{
"id": 4,
"body": "How long does it last?",
"date_written": 1594341317,
"asker_name": "funnygirl",
"helpful": 6,
"reported": 0,
"answers": "{\"65\": {\"id\": 65, \"body\": \"It runs small\", \"date\": 1605784307, \"helpful\": 1, \"reported\": 0, \"answerer_name\": \"dschulman\"}, \"89\": {\"id\": 89, \"body\": \"Showing no wear after a few months!\", \"date\": 1599089610, \"helpful\": 8, \"reported\": 0, \"answerer_name\": \"sillyguy\"}}"
},
{etc},
{etc}]
Before sending the result of my database query back to the client, I need to parse the answers value. My initial thought was to make the result a promise, then use a forEach loop to run through each object and parse 'answers' if it is not undefined. My code to do that is organized as follows:
db.query(query, [req.query['product_id'], req.query['count']], (error, results) => {
if (error) {
console.log('err err ', error);
}
if (!results[0]) {
res.json('No questions found')
} else {
console.log(results)
Promise.resolve(results.forEach(result => {
if (result['answers'] !== undefined) {
JSON.parse(result['answers']);
}
return results;
}))
.then(results => {
console.log(results)
})
res.json(results.splice(0, req.query['count']));
}
})
The console log in my 'then' block returns undefined. I also tried using results.map(), but this logged a bunch of empty arrays in the then block. Any advice on how to parse the 'answers' values when they are not null for an array of objects much appreciated!
Just a thought, have you tried just iterating results and updating the answers property without a Promise?:
db.query(query, [req.query['product_id'], req.query['count']], (error, results) => {
if (error) {
console.log('err err ', error);
}
if (!results[0]) {
res.json('No questions found')
} else {
console.log(results)
results.forEach(result => {
result.forEach((obj) => {
obj.answers = JSON.parse(obj.answers);
});
});
res.json(results.splice(0, req.query['count']));
}
});