将包含HTML表格源代码的字符串转换为javascript对象数组的简单/优雅方法是什么?
它会将每个<tr>
转换为一个对象,并将每个<td>
转换为一个对象属性。
不会从表中提取属性名称,它们已经定义。
例如,将此代码作为字符串传递给javascript函数:
<table>
<tr>
<td>2280</td>
<td>23020044623</td>
<td>RTS</td>
<td>EUR</td>
<td>1</td>
<td>29/07/2015</td>
<td>10/07/2017</td>
<td>no</td>
</tr>
<tr>
<td>2281</td>
<td>23020011223</td>
<td></td>
<td>GBP</td>
<td>0,78</td>
<td>10/10/2013</td>
<td>10/10/2018</td>
<td>Occult</td>
</tr>
</table>
将返回:
// Properties names are known
[
{
prop1: '2280',
prop2: '23020044623',
prop3: 'RTS',
prop4: 'EUR',
prop5: '1',
prop6: '29/07/2015',
prop7: '10/07/2017',
prop8: 'no'
},
{
prop1: '2281',
prop2: '23020011223',
prop3: '',
prop4: 'GBP',
prop5: '0,78',
prop6: '10/10/2013',
prop7: '10/10/2018',
prop8: 'Occult'
}
]
答案 0 :(得分:3)
您可以使用此ES6功能:
var props = ['prop1', 'prop2', 'prop3', 'prop4', 'prop5', 'prop6', 'prop7', 'prop8'];
function fromTable(html) {
return Array.from(
new DOMParser().parseFromString(html, "text/html").querySelectorAll('tr'),
row => [...row.cells].reduce(
(o, cell, i) => (o[props[i]] = cell.textContent, o), {}));
}
// Sample data:
var html = `<table>
<tr>
<td>2280</td>
<td>23020044623</td>
<td>RTS</td>
<td>EUR</td>
<td>1</td>
<td>29/07/2015</td>
<td>10/07/2017</td>
<td>no</td>
</tr>
<tr>
<td>2281</td>
<td>23020011223</td>
<td></td>
<td>GBP</td>
<td>0,78</td>
<td>10/10/2013</td>
<td>10/10/2018</td>
<td>Occult</td>
</tr>
</table>`;
// Get object from HTML:
var res = fromTable(html);
// Output result
console.log(res);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
答案 1 :(得分:2)
您可以解析HTML并使用map和reduce来返回预期的对象数组
var html = '<table><tr><td>2280</td><td>23020044623</td><td>RTS</td><td>EUR</td><td>1</td><td>29/07/2015</td><td>10/07/2017</td><td>no</td></tr><tr><td>2281</td><td>23020011223</td><td></td><td>GBP</td><td>0,78</td><td>10/10/2013</td><td>10/10/2018</td><td>Occult</td></tr></table>';
var parser = new DOMParser();
var doc = parser.parseFromString(html, "text/html");
var obj = [].map.call(doc.querySelectorAll('tr'), tr => {
return [].slice.call(tr.querySelectorAll('td')).reduce( (a,b,i) => {
return a['prop' + (i+1)] = b.textContent, a;
}, {});
});
console.log(obj)
&#13;
答案 2 :(得分:0)
遍历每个<tr>
,然后遍历每个<td>
。
(function() {
var ob = [];
$('table tr').each(function() {
var row = {};
$(this).children().each(function(ind) {
row['prop' + (ind + 1)] = $(this).text();
})
ob.push(row);
});
console.log(ob);
})();
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<table id="table">
<tr>
<td>2280</td>
<td>23020044623</td>
<td>RTS</td>
<td>EUR</td>
<td>1</td>
<td>29/07/2015</td>
<td>10/07/2017</td>
<td>no</td>
</tr>
<tr>
<td>2281</td>
<td>23020011223</td>
<td></td>
<td>GBP</td>
<td>0,78</td>
<td>10/10/2013</td>
<td>10/10/2018</td>
<td>Occult</td>
</tr>
</table>