I am trying to iterate (with a for..in loop) multiple entries and output them as a json object. Where I am running into difficulty is that the data only outputs a single list entry, and not all of them. Using AxiosJS in Node, I've found it outputs in the exact format I'd like. I'm unsure how to format my loop in order to output like this:
{
"Cardio_ETC": {
"name": "John",
"shift": "7a-7a",
"service": "ETC Cardiology",
"Office": "1234",
"cell": ""
},
"Cardio_STEMI": {
"name": "Pran",
"shift": "7a-7a",
"service": "STEMI Cardiology",
"Office": "34561321",
"cell": ""
},
"fastTrack1": {
"name": "Bob",
"shift": "7a-7p",
"service": "Fasttrack",
"Office": "X533 tel",
"cell": "X533"
},...etc
Here is my current code:
.then((data)=>{
connection.query("SELECT * FROM amion_onCall", function (err, result, fields){
//format results here
var fixed = new Object();
let i;
for (i in result){
aName = result[i].name;
serv = result[i].specialty;
aServ = serv.replace(' ','_');
aShift = result[i].shift;
aOff = result[i].office;
aCell = result[i].cell;
aTag = result[i].tag;
var data = {name:aName, service: aServ, shift: aShift, office: aOff, cell: aCell, tag: aTag};
Object.assign(fixed, data);
console.log(fixed);
What is the best way to format this for..in loop in order to output the above json?
-
Please Upvote my question if you can, I don't have enough reputation in order to upvote your answers (I'm new)!Jrapa86– Jrapa862020年06月25日 13:00:17 +00:00Commented Jun 25, 2020 at 13:00
-
I did not understand anything. what result do you want from which source? why add an SQL query to this problem?Mister Jojo– Mister Jojo2020年06月25日 13:06:02 +00:00Commented Jun 25, 2020 at 13:06
1 Answer 1
In your case, If you want to use for in you can do this
const obj = {};
for (i in result) {
obj[result[i].tag] = {
name: result[i].name,
service: result[i].specialty.replace(' ', '_'),
shift: result[i].shift,
office: result[i].office,
cell: result[i].cell,
}
}
console.log(obj) // will have your answer
but I recommend using reduce
.then((data) => {
connection.query("SELECT * FROM amion_onCall",
function (err, result) {
const obj = result.reduce((o, item) => {
o[item.tag] = {
name: item.name,
service: item.specialty.replace(' ', '_'),
shift: item.shift,
office: item.office,
cell: item.cell,
}
return o
}, {});
console.log(obj)
})
})
Sign up to request clarification or add additional context in comments.
Comments
lang-js