I've been trying to understand and master creating json objects with javascript, however I cannot seem to figure out how to (first iterate something, and use that value as my key). My second problem is when I see my json result, it always seems to be nested with a preceding blank item before it. Here is what I mean:
My current portion of code is:
.then((data)=>{
connection.query("SELECT * FROM amion_onCall", function (err, result, fields){
const fixed = [];
let i;
for (i in result){
aName = result[i].name;
aServ = result[i].specialty;
aShift = result[i].shift;
aOff = result[i].office;
aCell = result[i].cell;
aTag = result[i].tag;
var data = {aServ: {name:aName, service: aServ, shift: aShift, office: aOff, cell: aCell, tag: aTag}};
// console.log(data);
fixed.push(data);
}
fs.writeFile('./data/json/newAmion.json', JSON.stringify(fixed), function(err){
if (err) throw err;
console.log("Wrote New Amion");
});
});
})
The output in my json viewer is:
[
{
"aServ": {
"name": "Dr.John",
"service": "Cardiology",
"shift": "7a-7p",
"office": "123",
"cell": "123-456-789",
"tag": "no tags"
}
},
...and so on for my ~150 entries.
Problem #1: I want to move this up one full level. I'm not sure how to do that, or why it starts so deeply nested.
Problem #2: When I iterate aServ, I want the actual value to be output in the beginning of my json. My current code prints "aServ" statically for everyone...I don't want to do that. For example, this is how I am trying to get my json to output:
{
"Cardiology": {
"name": "Dr.John",
"service": "Cardiology",
"shift": "7a-7p",
"office": "123",
"cell": "123-456-789",
"tag": "no tags"
},
"Pulmonology": { ...and so on
}