所以我终于得到了 star wars API 来显示来自“people”对象的每个 Angular 色的名字,这个 JSON 数组取自 https://swapi.co/api/people/在 Vanilla Javascript 中。但是,我需要根据 https://swapi.co/api/species/1/ 的特定值对数据结果进行排序或过滤。我当前的代码,当我运行它时,它会显示包含所有人类物种名称的表格,我只需要人类物种。这是我的代码:
const url = 'https://swapi.co/api/species/1/?format=json';
function fetchData(url) {
return fetch(url).then((resp) => resp.json());
}
function constructTableRow(data) {
const row = document.createElement('tr');
const {
name,
height,
mass,
hair_color
} = data;
row.appendChild(constructElement('td', name))
row.appendChild(constructElement('td', height))
row.appendChild(constructElement('td', mass))
row.appendChild(constructElement('td', hair_color))
return row;
}
function constructElement(tagName, text, cssClasses) {
const el = document.createElement(tagName);
const content = document.createTextNode(text);
el.appendChild(content);
if (cssClasses) {
el.classList.add(...cssClasses);
}
return el;
}
const swTable = document.getElementById('sw-table').getElementsByTagName('tbody')[0];
fetchData('https://swapi.co/api/people/').then((data) => {
data.results.forEach(result => {
const row = constructTableRow(result);
swTable.appendChild(row);
});
});
<table id=sw-table><tbody></tbody></table>
JSON 端点来自 https://swapi.co/api/people/
如何让表格只显示人类的数据?
最佳答案
使用 filter
怎么样?
const humansOnly = result.filter(p => p.species.indexOf('https://swapi.co/api/species/1/') !== -1);
关于javascript - 如何在 Javascript 中按值排序或过滤 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49638540/