javascript - 如何让我的代码排序数据从 Reddit 提取为 JSON 文本?
问题描述
[按属性值对对象数组进行排序]
我想比较赞成票的数量并进行排序,但是在理解如何从我的 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);**
});
});
错误:未捕获(承诺中)类型错误:无法读取未定义的属性“排序”
解决方案
这是您应该使用的:
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
如果 ups 多于则返回负数,如果a
ups 多于则返回b
正数,如果b
ups数量a
相同则返回 0
推荐阅读
- python - 生成包含模态值的新列
- javascript - 我需要将下一行放入带有 java 值的弹出 javascript 字符串中
- linux - Google Cloud Run 和系统功能
- c++ - 地图插入替换以前输入的值
- javascript - 首先隐藏然后显示多个 tbody 组基于使用 jQuery 的下拉选择
- excel - 查看 if / if 在 if 语句中关联的结果
- yii2 - Yii2 - Web 和控制台应用程序中常见的别名
- android - iOS 平板电脑上应用的扩展功能
- python-3.x - 在 DF 中输入缺失数据和预测数据
- c# - 在上下文中查找用户角色。没有 Identity Manager 的用户?