代码之家  ›  专栏  ›  技术社区  ›  Carol.Kar

从JSON对象获取唯一值

  •  0
  • Carol.Kar  · 技术社区  · 7 年前

    我正在尝试从公众那里获取所有的算法来挖掘API:

    var lookup = {}
    var result = []
    
    axios.get('https://whattomine.com/calculators.json')
      .then(function(response) {
        console.log(response)
        for (var item, i = 0; item = response["coins"][i++];) {
          var algorithm = item.algorithm
    
          if (!(algorithm in lookup)) {
            lookup[algorithm] = 1
            result.push(algorithm)
          }
        }
        console.log(result)
      })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>

    如您所见,我使用AXIOS来查询API。然后我想过滤所有不在查找中的算法。

    因此,我希望: []

    但是,我现在得到 ['Keccak', 'Scrypt-OG', 'X11'] 后退。

    有什么我做错了的建议吗?

    谢谢你的回复!

    2 回复  |  直到 7 年前
        1
  •  2
  •   blex    7 年前

    正如其他人所说, response 是一个具有 data 属性,包含实际响应。另外,您试图像数组一样循环它们,但它是一个以硬币名称作为属性的对象。 Lodash 可以让你的生活更轻松:

    axios.get('https://whattomine.com/calculators.json')
      .then(response => {
        const coins = response.data.coins;
        const result = _.uniq(_.map(coins, item => item.algorithm));
        console.log(result);
      });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
    • _.map() 允许您循环数组或对象,这在这里很有用。

    • _.uniq() 将从值数组中删除任何重复项。

        2
  •  2
  •   joaner    7 年前

    您应该看到数据结构:的键 coins 是字符串,不是像我这样的数字++

    var lookup = {}
    var result = []
    
    axios.get('https://whattomine.com/calculators.json')
      .then(function(response) {
        for (var key in response.data["coins"]) {
          var item = response.data["coins"][key]
          var algorithm = item.algorithm
    
          if (!(algorithm in lookup)) {
            lookup[algorithm] = 1
            result.push(algorithm)
          }
        }
        console.log(result)
      })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>