簡體   English   中英

使用 For 循環動態創建 Object

[英]Dynamically Create Object with For Loop

我正在嘗試迭代(使用 for..in 循環)多個條目和 output 它們作為 json object。 我遇到困難的地方是數據只輸出一個列表條目,而不是全部。 在 Node 中使用 AxiosJS,我發現它以我想要的確切格式輸出。 我不確定如何格式化我的循環以便 output 像這樣:

{
  "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

這是我當前的代碼:

.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);

為了 output 上面的 json 格式化這個 for..in 循環的最佳方法是什么?

在你的情況下,如果你想使用 for in 你可以這樣做

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

但我建議使用 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)
    })
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM