javascript - 将对象数组排序为更干净的数组
问题描述
我正在尝试将对象数组排序为具有特定属性的更清晰的对象数组。
我正在获取一个返回大量对象的 api
目前我还没有弄清楚如何获得这样的数组:
results= [
{'author' : Mister1,'url':'http://url1.com','score':400},
{'author' : Mister2,'url':'http://url2.com','score':350},
{'author' : Mister3,'url':'http://url3.com','score':500},
{'author' : Mister4,'url':'http://url1.com','score':456},
]
这是我的代码:
function fetchSearchTopStories(term) {
axios.get(`https://www.reddit.com/r/${term}/top.json`, { responseType: 'json' }).then(response => {
const tab = (response.data.data.children)
for (let i = 0; i < tab.length; i++) {
results.url= tab[i].data.url
results.author = tab[i].data.author
results.score= tab[i].data.score
console.log(results)
}
return results
})
}
不幸的是,这不是在数组中插入,而是每次创建一个只有一个字段而不是多个字段的新数组。
非常感谢
解决方案
您还可以使用ES6和对象解构使您的代码更简洁:
function fetchSearchTopStories(term) {
axios.get(`https://www.reddit.com/r/${term}/top.json`, {
responseType: 'json'
}).then(r => console.log(r.data.data.children.map(({data}) => {
let {url, author, score} = data
return {url, author, score}
})))
}
fetchSearchTopStories('javascript');
<script src="https://unpkg.com/axios@0.18.0/dist/axios.min.js"></script>
推荐阅读
- xml - 如何使用 xmllint xpath 获取具有相同标签名称的所有属性
- arrays - PropTypes:初始 useState 返回对象并在添加第一项时未通过 propTypes 检查
- bash - 将 shell 脚本中的文件与 md5sum 进行比较,并为更改的文件创建 csv
- python - 使用 psycopg2 构建动态 INSERT 查询
- c# - 不能在@html 元素中调用方法吗?
- python - 按类别内的标题过滤(多对多)
- swift - 在 Xcode11.4 beta 中测试静默推送通知
- postgresql - 降低 PostgreSQL 数据库的导入性能
- python-3.x - Selenium webdriver 打开 url 但随后给出超时异常
- mocha.js - 使用 beforeEach 插入虚拟数据