2017-08-31 83 views
1

我需要得到這個對象:變量作爲JavaScript屬性名對象常量

{ 
    "1": { 
    "epg": { 
     "title1": "TITLE", 
     "start1": "10:00", 
     "stop1": "12:50", 
     "description1": "DESC", 
     "percent1": "17", 
     "step1": "2" 
    } 
}, 
    "2": { 
    "epg": { 
     "title2": "TITLE", 
     "start2": "13:50", 
     "stop2": "14:00", 
     "description2": "DESC", 
     "percent2": "-262", 
     "step2": "7" 
    } 
    } 
} 

我寫這篇文章的代碼:

/* MAKE - 5 shows epg */ 
for (i = 0; i < 2; i++) { 
    data.push({i: {"epg": {"title1": "", "start1": "", "stop1": "", "description1": "", "percent1": "", "step1": ""}}}); 
}; 

/* SEND - 5 shows epg */ 
res.json(data); 

,我得到這樣的輸出:

[{"i":{"epg":{"title1":"","start1":"","stop1":"","description1":"","percent1":"","step1":""}}},{"i":{"epg":{"title1":"","start1":"","stop1":"","description1":"","percent1":"","step1":""}}}] 

這是不正確的......你能否給我提示功能或如何去做。

+1

'數據[i] = {EPG:...};' –

回答

0

您可以使用一個對象並使用遞增的索引進行賦值。

var data = {}, 
 
    j; 
 

 
for (i = 0; i < 2; i++) { 
 
    j = i + 1; 
 
    data[j] = { epg: {} }; 
 
    data[j].epg['title' + j] = ''; 
 
    data[j].epg['start' + j] = ''; 
 
    data[j].epg['stop' + j] = ''; 
 
    data[j].epg['percent' + j] = ''; 
 
    data[j].epg['step' + j] = ''; 
 
} 
 

 
console.log(data);

+0

由於這是我need..but一件事我忘了ask..how分配號碼,它看起來像這樣:title1 title2 title3我嘗試使用「標題」+我但我得到錯誤消息意外的標記+ – John