配列からテーブルを作る2
配列からテーブルを作る場合、セルを結合したりclassName を指定したい時がある。そこで配列のセルに該当するテキストから colSpan , rowSpan などを取り出せるようにした。
- 文字列の先頭が "#" ならば TH 要素になる
- ”!r4c2 def" ならば rowSpan=4, colspan=2, textContent = "def" となる
- "!{"className":"red"} ghi ならば class="red", textContent = "ghi" となる。 { } で囲まれる部分は、JSON 形式に変換されるのでダブルクォーテーションを適材適所に使用すること。また {"innerHTML":"<a href='xxx'>Test</a>"}とすれば子要素以降も文字列から生成できる。その場合は適切に文字をエスケープすること。
let ary = [ ["#!r4{"className":"red"} abc", "#!c4 def, ... ], [...], ... ]
function ary2thead (ary = [ ], thead = document.createElement ('thead')) { for (let row of ary) thead.insertRow().append(...row.map(cell=>{ let [, th, rowSpan, colSpan, json, textContent = ''] = (new RegExp ('^(#)?(?:!(?=[rc\\{])(?:r([2-9]|[1-9]\\d+)|r[01]|r0\\d+)?(?:c([2-9]|[1-9]\\d+)|c[01]|c0\\d+)?({.+})?)?\\s*(.*)\\s*$','g')).exec (cell) ?? [ ]; return Object.assign (document.createElement (th ? 'th': 'td'), Object.entries ({rowSpan, colSpan, textContent}).reduce((a,[b,c])=>((c===undefined||(a[b]=c)),a), {}), json ? JSON.parse(json): {}); })); return thead; }
短く
const ary2thead= (a=[],b=document.createElement('thead'))=>{ for(let c of a)b.insertRow().append(...c.map(d=>{ let[,e,f,g,h,i='']=(new RegExp('^(#)?(?:!(?=[rc\\{])(?:r([2-9]|[1-9]\\d+)|r[01]|r0\\d+)?(?:c([2-9]|[1-9]\\d+)|c[01]|c0\\d+)?({.+})?)?\\s*(.*)\\s*$','g')).exec(d)??[]; return Object.assign(document.createElement(e?'th':'td'),Object.entries({rowSpan:f,colSpan:g,textContent:i}).reduce((j,[k,l])=>((l===undefined||(j[k]=l)),j),{}),h?JSON.parse(h):{}); }));return b};