首页 > 解决方案 > 将对象数组排序为更干净的数组

问题描述

我正在尝试将对象数组排序为具有特定属性的更清晰的对象数组。

我正在获取一个返回大量对象的 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
    })
}

不幸的是,这不是在数组中插入,而是每次创建一个只有一个字段而不是多个字段的新数组。

非常感谢

标签: javascriptarrays

解决方案


您还可以使用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>


推荐阅读