【问题标题】:How to sort or filter JSON data by value in Javascript如何在 Javascript 中按值对 JSON 数据进行排序或过滤
【发布时间】:2018-09-13 06:42:42
【问题描述】:

所以我终于得到了星球大战 API 来显示“人”对象中每个角色的名称,这个 JSON 数组取自香草 Javascript 中的https://swapi.co/api/people/。但是,我需要根据我拥有的当前代码 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/

如何让表格只显示人类物种的数据?

【问题讨论】:

    标签: javascript arrays json sorting


    【解决方案1】:

    使用filter怎么样?

    const humansOnly = result.filter(p => p.species.indexOf('https://swapi.co/api/species/1/') !== -1);
    

    【讨论】:

      【解决方案2】:

      物种 API 返回的 JSON 包含一个 people 数组。因此,不要过滤 people,而是遍历 people 数组。

      但是,由于 SWAPI rate limiting,这可能会导致问题。

      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(url).then(data =>
        data.people.forEach(personUrl =>
          fetchData(personUrl).then(result => {
            const row = constructTableRow(result);
            swTable.appendChild(row);
          })
        )
      );
      <table id=sw-table>
        <tbody></tbody>
      </table>

      【讨论】:

      • 另外,当我将 .sort() 添加到名称时,它会中断。我是否必须创建一个单独的函数来按字母顺序排序?
      • 没有要排序的名称数组。 data.people 是一个 URL 数组。所以不清楚你要排序什么。
      • 啊,我明白了。谢谢
      【解决方案3】:

      好吧,您知道https://swapi.co/api/species/1/ 是人类,所以您可以使用filter 来检查species 数组中是否存在该网址。

      const isHuman = guy=>~guy.species.indexOf('https://swapi.co/api/species/1/');
      

      您可以使用indexOf 来确定数组中是否存在元素。如果不存在则返回负一,因此使用bitwise NOT (~) 使其存在时为真,不存在时为假。

      然后您可以在循环之前过滤该函数上的结果..

      data.results.filter(isHuman).forEach(result => {....});
      

      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];
      
      const isHuman = guy=>~guy.species.indexOf('https://swapi.co/api/species/1/');
      
      fetchData('https://swapi.co/api/people/').then((data) => {
          data.results.filter(isHuman).forEach(result => {
              const row = constructTableRow(result);
              swTable.appendChild(row);
          });
      });
      &lt;table id=sw-table&gt;&lt;tbody&gt;&lt;/tbody&gt;&lt;/table&gt;

      【讨论】:

        【解决方案4】:

        另一个示例使用.filter().includes()(代替检测负索引):

        fetchData('https://swapi.co/api/people/').then(data => {
            data.results
                .filter(person => person.species.includes("https://swapi.co/api/species/1/"))))
                .forEach(human => swTable.appendChild(constructTableRow(human)))
        });
        

        【讨论】:

          【解决方案5】:

          这行得通吗?

              fetchData('https://swapi.co/api/people/').then((data) => {
          
                 data.results.forEach(result => {
                 const row = constructTableRow(result);
                 if(result.species === "https://swapi.co/api/species/1/") {
                     swTable.appendChild(row);
                  }
             });
          

          【讨论】:

            猜你喜欢
            • 2018-12-22
            • 2012-11-06
            • 2018-02-04
            • 2016-07-26
            • 2021-07-01
            • 2014-05-22
            • 2021-06-21
            • 2016-10-30
            • 1970-01-01
            相关资源
            最近更新 更多