--- pagetitle: Prepare Data for htmlwidget example: title: Prepare Data for htmlwidget instructions: |- An R list has been converted to JSON for use in an htmlwidget, but the `.data` property is still in "R" format. Assume that the first key (column) should be used as `labels` and the remaining columns should be used as the `datasets`. Reformat the data to follow the pattern in the example below and replace the `x.data` property. hint: |- ```js x.data = { labels: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], datasets: [ { name: "R", values: [18, 40, 30, 35, 8, 52, 17, -4] }, { name: "Python", values: [30, 50, -10, 15, 18, 32, 27, 14] } ] } ``` runtime: repl mode: document: html initial: js: |- let x = document.getElementById('chart-opts') x = JSON.parse(x.textContent) // create an empty object to hold the formatted chart data const chartData = {labels: [], datasets: []} // Get keys of data, assume that first entry is for labels, the rest are data // chartData.labels = ... // Create an appropriate object for each column, reformat data and add to chartData x.data = chartData css: ~ solution: js: |- let x = document.getElementById('chart-opts') x = JSON.parse(x.textContent) // create an empty object to hold the formatted chart data const chartData = {labels: [], datasets: []} // Get keys of data, assume that first entry is for labels, the rest are data let labelColumn = Object.keys(x.data)[0] let columns = Object.keys(x.data).slice(1) console.log({labelColumn, columns}) // First column in x.data is the labels chartData.labels = x.data[labelColumn] // Create an appropriate object for each column, reformat data and add to chartData columns.forEach(function(col) { chartData.datasets.push({name: col, values: x.data[col]}) }) x.data = chartData css: ~ output: js4shiny::html_document_js4shiny ---