2014-10-28 39 views
1

如何將索引和值添加到對象,下面是我的代碼,我試圖在循環中添加索引和值,但它顯示錯誤undefined is not an object ($data.file_list_image.i.sequence),爲什麼以及如何解決它?如何將索引和值添加到對象?

試圖讓JSON數據發送到服務器端

希望信息

$data = {file_list_image: {0: {sequence: 1, intro: }, 1: {sequence: 1, intro: }, }} 

JS

var $el = $content_list.find('.content-list-gallery-file-list'); 
var file_length = $el.length; 
var file_image_length = 0; 
var file_embed_youtube_length = 0; 

for (var i = 0; i < file_length; i++) { 
    if ($el.eq(i).attr('data-type') == 0) { // console.log('img'); 
     file_image_length++; 
    } else if ($el.eq(i).attr('data-type') == 1) { // console.log('video'); 
     file_embed_youtube_length++; 
    } 
} 

var $data = {}; 


for (var i = 0; i < file_image_length; i++) { 
    var $file_list = $el.filter(function() { 
     return $(this).attr('data-type') == 0 && $(this).attr('data-tmp-id') == i; 
    }); 

    var sequence = $file_list.attr('data-sequence'); 
    var intro = $file_list.find('.intro textarea').val(); 


    $data.file_list_image.i.sequence = sequence; 
    $data.file_list_image.i.intro = intro; 
} 

console.log($data); 

HTML的如何可以做到

<div class="content_list"> 
    <div class="content-list-gallery-file-list" data-type="0" data-tmp-id="1" data-sequence="0"> 
    <div class="intro"><textarea></textarea></div> 
    </div> 
    <div class="content-list-gallery-file-list" data-type="0" data-tmp-id="0" data-sequence="1"> 
    <div class="intro"><textarea></textarea></div> 
    </div> 
    <div class="content-list-gallery-file-list" data-type="1" data-tmp-id="2" data-sequence="2"> 
    <div class="intro"><textarea></textarea></div> 
    </div> 
</div> 
+1

'file_list_image'是一個對象數組嗎?分享您正在使用的數據的結構。一些例子會更清晰。但是,如果它是一個對象數組,然後嘗試執行'$ data.file_list_image [i] .sequence'。另外,我不明白你爲什麼將變量'data'命名爲'$ data'。這是一個誤導。 – 2014-10-28 09:35:33

+0

請完整發布您的代碼 – 2014-10-28 09:36:47

+0

感謝您的回覆,這就是我所有的代碼,我試圖使數據類似{file_list_image:{0:{sequence:1,intro:letter},1:{sequence:0,}} – vibskov 2014-10-28 09:41:12

回答

1

例通過初始化對象pr operties在正確的時間:

Fiddle example

var $data = {}; 
$data.file_list_image = {}; 
for (var i = 0; i < 5; i++) 
{ 
    $data.file_list_image[i] = {}; 
    $data.file_list_image[i]["sequence"] = "seq" + i; 
    $data.file_list_image[i]["intro"] = "in" + i; 
} 
console.log($data); 

順便說一句,$data.file_list_image[i]["sequence"](與intro相同),也可以$data.file_list_image[i].sequence

Fiddle example with original HTML

相關問題