2013-10-18 56 views
1

我有一張表。 HTML將表值轉換爲JSON值

<div class="row-fluid"> 
    <table class="table table-striped" id="table-visual-features"> 
     <thead> 
      <tr> 
       <th>Visual Feature</th> 
       <th>Type [currently not used]</th> 
       <th>Description</th> 
       <th>Actions</th> 
      </tr> 
     </thead> 
     <tbody> 
      <tr><td>A11</td><td>Numeric [1..30]</td><td>Values to be mapped to the S1-axis</td><td><button class="action-change">edit</button> <button class="btn btn-mini btn-danger action-remove-visual-feature">remove</button></td></tr> 
      <tr><td>A21</td><td>Numeric [1..10 ]</td><td>Values to be mapped to the S2-axis</td><td><button class="action-change">edit</button> <button class="btn btn-mini btn-danger action-remove-visual-feature">remove</button></td></tr> 
      <tr><td>A31</td><td>Numeric [1..20 ]</td><td>Values to be mapped to the S3-axis</td><td><button class="action-change">edit</button> <button class="btn btn-mini btn-danger action-remove-visual-feature">remove</button></td></tr> 


     </tbody> 
    </table> 
</div> 

我想我的價值從錶轉換成這種形式

var features = { 
    features: { 
     "A11": {"type_feature": "Numeric [1..30]", "description_feature": "Values to be mapped to the S1-axis"}, 
     "A21": {"type_feature": "Numeric [1..10]", "description_feature": "Values to be mapped to the S2-axis"}, 
     "A31": {"type_feature": "Numeric [1..20]", "description_feature": "Values to be mapped to the S3-axis"} 
    } 
}; 

我採取的第一個單元格的值的行中,它是「A11」。 行中第二個單元格的值是「Numeric [1..30]」。 行中第三個單元格的值是「要映射到S1軸的值」。 我們首先進入

features: { 
      "A11": {"type_feature": "Numeric [1..30]", "description_feature": "Values to be mapped to the S1-axis"}} 

這是我的jsfiddle http://jsfiddle.net/7q3KP/

請幫我轉換價值。謝謝你在前進

+0

不清楚你想說什麼? –

+1

FTI:這不是JSON值。這是一個JavaScript對象。 JSON是類似於JavaScript語法的數據的*字符串表示*。如果它不是字符串,那不是JSON。 –

+0

@Subhash:他想將HTML表格「轉換」爲JavaScript對象。 –

回答

4

試試這個

var features = {features:{}}; 
$('tr:not(:first)').each(function() { 
    var name = $(this).find('td:first').text(); 
    features["features"][name] = { 
     "type_feature": $(this).find('td:eq(1)').text(), 
     "description_feature": $(this).find('td:eq(2)').text() 
    } 
}); 
console.log(features); 

DEMO

+2

+1了不起的工作。如此簡單而短暫。 – pregmatch

+0

+1擊敗我! –

+1

yahooooooooooooooooooooo!感謝您的解決方案。這對我來說是非常有幫助的!!! – user2894088

2

此代碼將遍歷所有的行和提取數據到你的對象特點:

var features = { features: {}}; 

$('#table-visual-features tbody tr').each(function() { 
    var cells = $(this).find('td'); 
    features.features[cells.eq(0).text()] = { 
     "type_feature": cells.eq(1).text(), 
     "description_feature": cells.eq(2).text() 
    }; 
}); 

console.log(features); 

的jsfiddle示例 - http://jsfiddle.net/Bdv4L/

+0

作爲接受的答案,我很感激,它應該去安東,因爲他在我做之前兩分鐘發佈基本上完全相同的答案。 –

+0

感謝您的解決方案。這對我來說是非常有幫助的!!! – user2894088