javascript - 如何让我的代码对从 Reddit 获取的 JSON 文本数据进行排序?

标签 javascript arrays json api sorting

[按属性值对对象数组进行排序]

我想比较点赞数和排序,但我无法理解如何从我的 api 获取对象“ups”。 我创建了比较函数并且我想调用它。我可能在错误的对象上调用它。

 function fetchData(url) {
    return fetch(url).then((resp) => resp.json());
}

function createTableRow(data) {
    const tableRow = document.createElement('tr');
    const {
        title,
        ups,
        downs,
        score,
        num_comments,
        created
    } = data;
    console.log(ups);
    tableRow.appendChild(createElement('td', title))
    tableRow.appendChild(createElement('td', ups))
    tableRow.appendChild(createElement('td', downs))
    tableRow.appendChild(createElement('td', score))
    tableRow.appendChild(createElement('td', num_comments))
    tableRow.appendChild(createElement('td', created))
    return tableRow;
}


function createElement(tag_name, text) {
    const el = document.createElement(tag_name);
    const content = document.createTextNode(text);
    el.appendChild(content);
    return el;
}

**function compare(a,b) {
    if(a.ups<b.ups) {
        return -1;
    }
    if(a.ups>b.ups){
        return 1;
    }
    return 0;
}** 


const butt = document.getElementById('button');

const swTable = document.getElementById('sw_table').getElementsByTagName('tbody')[0];


fetchData('https://www.reddit.com/r/funny.json')
.then(data => {
    data.data.children.forEach(result => {
    const table = createTableRow(result.data);
    swTable.appendChild(table);
   // butt.onclick(sortData(ups));
   **data.data.children.ups.sort(compare);**
});
});

错误: 未捕获( promise 中)类型错误:无法读取未定义的属性“排序”

最佳答案

这是您应该使用的内容:

fetchData('https://www.reddit.com/r/funny.json')
  .then(data => {
    const sortedResults = data.data.children.sort((a,b) => b.data.ups - a.data.ups)
    sortedResults.forEach(result => {
      const row = createTableRow(result.data);
      swTable.appendChild(row);
    })
  });
});
  • 您必须直接对结果进行排序
  • a.data.ups - b.data.ups 如果 a 的 ups 多于 b,则返回负数,a如果 b 的 ups 数量多于 a,则为正数;如果它们的 ups 数量相同,则为 0

关于javascript - 如何让我的代码对从 Reddit 获取的 JSON 文本数据进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56219914/

相关文章:

javascript - 需要一些帮助来使用 Javascript/jQuery 删除 ' € ' 标志

java - 当我们允许使用Object类创建异构数组时,java中的数组如何能够是同构的?

json - 跨域 $http 请求 AngularJS

javascript - 多模态语义 ui

javascript - 解析 json 数据失败 - jquery

javascript - 如何在编译后的函数中追加元素 - AngularJS

PHP:变量(数组)是函数吗?

mysql - 如何在 MySQL 中存储和获取封装的数组数据

javascript - 如何使用socket.io和node.js将数据写入JSON文件?

php - 如何使用 json_encode 调用 PHP 中的多个类?