Last active
February 5, 2021 23:02
-
-
Save mallendeo/798bc0881de67ead5fb9df4a222bf42a to your computer and use it in GitHub Desktop.
HTML Table to JSON
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { camelCase } from 'change-case' | |
// $: cheerio object | |
const tableToJson = ($, table) => { | |
const fields = $(table) | |
.find('thead tr th') | |
.map((_, el) => $(el).text().trim()) | |
.get() | |
const rows = $(table) | |
.find('tbody tr') | |
.map((_, row) => ({ | |
cells: $(row) | |
.find('td') | |
.map((_, cell) => $(cell).text().trim()) | |
.get(), | |
})) | |
.get() | |
return rows.map((row) => { | |
const item = {} | |
fields.forEach((field, index) => { | |
item[camelCase(field)] = row.cells[index] | |
}) | |
return item | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment