javascript - 如何在 Javascript 中按值排序或过滤 JSON 数据

标签 javascript arrays json sorting

所以我终于得到了 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/

相关文章:

javascript - 使用单个图像在图像上添加图像叠加层

javascript - Javascript、CoffeeScript、TypeScript、ES5 和 ES6 之间的关系

javascript - 通过变量访问元素

django - 从 django 序列化对象中删除 pk 字段

javascript - 当 status=false 时,alert(data.status) 失败,但当 status=true 时则不会失败

javascript - 如何为 Pug、React 和 ES6 设置 webpack

mysql - 使用 LabVIEW 和 Workbench 将数组插入 MySQL

javascript - Lodash - 根据条件合并两个数组的对象

json - 如何在JWT Header中设置JWT类型

javascript - 为什么 Infinity == Infinity == 1/0 是错误的?