Skip to content

Instantly share code, notes, and snippets.

@mallendeo
Last active February 5, 2021 23:02
Show Gist options
  • Save mallendeo/798bc0881de67ead5fb9df4a222bf42a to your computer and use it in GitHub Desktop.
Save mallendeo/798bc0881de67ead5fb9df4a222bf42a to your computer and use it in GitHub Desktop.
HTML Table to JSON
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