В коде я могу получить json данные и программно поместить их в таблицу. Здесь у вас есть код, который вы можете запустить. Теперь моя проблема в том, как отфильтровать заголовок? Как видите, метод forEach может выполнять итерацию по всем ключам файла json (идентификатор, имя, имя пользователя, электронная почта, адрес, телефон, веб-сайт, компания). Но как можно фильтровать, скажем, ключ «nam», чтобы мой ttle был «name»? Возможно, метод Array.prototype.filter () - лучшее решение, но я не могу его применить.
Здесь вы можете найти отлично работающий код LINK Codepen Code
function search() {
var queryURL = "https://jsonplaceholder.typicode.com/users";
fetch(queryURL)
.then(response=> response.json())
//arrow function by Mauro - works fine!
.then(data=>displayUsersAsATable(data))
.catch(function (error) {
console.log('Error during fetch: ' + error.message);
});
}
//questa è una variazione
function displayUsersAsATable(data) {
// users is a JavaScript object
// empty the div that contains the results
var usersDiv = document.querySelector("#users");
usersDiv.innerHTML = "";
//create a table
var table = document.createElement("table");
// create a table Caption
var mycaption = table.createCaption();
mycaption.innerHTML = "Table Caption"
var tableBody = table.createTBody();
// creates and populate the table with users
// iterate on the array of users
data.forEach(currentUser=> {
var myhead = table.createTHead();
var headRow = myhead.insertRow();
var emailHead = document.createElement('th');
var nameHead = emailHead.cloneNode();
headRow.appendChild(emailHead);
headRow.appendChild(nameHead);
emailHead.innerHTML = '';
nameHead.innerHTML = {};
// creates a row
var row = table.insertRow();
// insert cells in the row
var nameCell = row.insertCell();
nameCell.innerHTML = currentUser.email;
var cityCell = row.insertCell();
cityCell.innerHTML = currentUser.address.city;
//nameHead.innerHTML = `${cityCell.innerHTML}`
nameHead.innerHTML=`${Object.keys(currentUser)}`
});
// adds the table to the div
usersDiv.appendChild(table);
}