2012-03-21 5 views
2

私は、私のページにいくつかのIDからい​​くつかのjsonを作成する必要がある状況があります。divのidからjson objまたはarrayを作成する方法は?

ここにいくつかのコードがあります。私は必要だと思う

ids: "167" 
comment: { 
    id: "129" 
    id: "130" 
} 

ids: "166" 
comment: { 
    id: "134" 
    id: "136" 
} 

:ともjsfiddle

<ul class="wall_message"> 
    <li id="167" class="msgid"> 
     <div class="wall_msg">text</div> 
     <div id="129" class="comments"> 
      <div class="wall_img">commemt</div> 
     </div> 
     <div id="130" class="comments"> 
      <div class="wall_img">commemt</div> 
     </div> 
    </li> 
    <li id="166" class="msgid"> 
     <div class="wall_img">text</div> 
     <div class="wall_msg"> 
      <div id="134" class="comments"> 
       <div class="wall_img">commemt</div> 
      </div> 
      <div id="136" class="comments"> 
       <div class="wall_img">commemt</div> 
      </div> 
     </div> 
    </li> 
</ul>​ 

var jsonObj = [] 
var jsonObj1 = []; 

$('.msgid').each(function(index,val){ 
    jsonObj.push({ids : $(this).attr('id')}); 
}); 

$('.comments').each(function(index,element){ 
    jsonObj1.push({id : $(this).attr('id')}); 
}); 

console.log(jsonObj); 
console.log(jsonObj1); 

これは私が結果がなるように、何とかそれらを結合する必要がjsonObj1

ためjsonObjおよび4のための2つのオブジェクトを返します。最初のforeachで別のforeachを実行し、他のidのjsonに追加します。ただし、どのように行うべきかわかりません。

任意のアイデア?

+4

有効なオブジェクトcontructではありません。キーは同じではありません。コメントの内側にはコメントの代わりに配列を入れることができます。{ id: "134" id: "136" } –

答えて

1
var jsonObj = []; 

$('.msgid').each(function(){ 
    var obj = { 
     id: this.id, 
     comments: [] 
    }; 
    $(".comments", this).each(function() { 
     obj.comments.push({ 
      id: this.id 
     }); 
    }); 
    jsonObj.push(obj); 
}); 

console.log(jsonObj); 

この意志出力:

[ 
    { 
     id: "167", 
     comments: [ 
      { 
       id: "129" 
      }, 
      { 
       id: "130" 
      } 
     ] 
    }, 
    { 
     .... 
    } 
] 
2

私はあなたが上記の構造に興味がある場合

jsonObj = [ 
      {'ids': '167', 'comments': ['129', '130']}, 
      {'ids': '166', 'comments': ['134', '136']} 
]; 

、コードの下を参照してください、以下のように構築異なるJSONを思い付い

DEMO

var jsonObj = []; 
var len, comments; 
$('.msgid').each(function(index){ 
    len = jsonObj.push({'ids' : $(this).attr('id')}); 
    comments = []; 
    $(this).find('.comments').each (function() { 
     comments.push($(this).attr('id')); 
    }); 
    jsonObj[len - 1]['comments'] = comments; 
}); 

console.log(jsonObj); 
4

AndreasALの答えのより簡潔なバリエーション:

var jsonObj = $(".msgid").map(function() { 
    var obj = { id: this.id }; 

    obj.comments = $(".comments", this).map(function() { 
     return { id: this.id }; 
    }).get(); 

    return obj; 
}).get(); 
+0

これはいいですね... – andlrc

関連する問題