This code defines a JavaScript function `dataFromRow` that extracts and...
August 22, 2025 at 06:53 PM
This code defines a JavaScript function dataFromRow
that extracts and converts data from a table row (row
) into an object, using a set of predefined headers as keys.
Here is a detailed explanation of what this code does:
-
Function Definition:
- The function
dataFromRow
takes two arguments:row
: A table row (<tr>
) element, typically representing a single row from an HTML table.headers
: An array of strings, where each string is a header corresponding to the table columns.
- The function
-
Fetching all
<td>
elements in the row:- The code uses
row.querySelectorAll('td')
to select all<td>
(table cell) elements in the row.
- The code uses
-
Mapping to Key-Value Pairs:
- The
[...row.querySelectorAll('td')]
converts theNodeList
of<td>
elements into an array so that it can be processed with.map
. - The
.map()
method is used to map each<td>
element and its index to a[key, value]
pair:headers[index]
: Retrieves the header at the same index as the column index of the<td>
element, which acts as the "key."td.textContent
: Extracts the text content of the<td>
element, which acts as the "value."
- The
-
Converting to an Object:
Object.fromEntries()
takes the array of[key, value]
pairs returned by.map()
and converts it into an object.
-
Return Value:
- The final object maps header names (from the
headers
array) to their corresponding cell values (from thetd
elements in the row).
- The final object maps header names (from the
Example Usage:
Suppose the HTML table row looks like this:
<tr>
<td>John</td>
<td>Doe</td>
<td>25</td>
</tr>
And the corresponding headers
array is:
const headers = ['firstName', 'lastName', 'age'];
Calling the function:
const row = document.querySelector('tr');
const data = dataFromRow(row, headers);
console.log(data);
The output would be:
{
firstName: 'John',
lastName: 'Doe',
age: '25'
}
In summary, this code takes an HTML table row and converts it into an object where column headers act as keys and the cell contents act as values.
Generate your own explanations
Download our vscode extension
Read other generated explanations
Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node