【问题标题】:Json : find the maximum numberJson : 找到最大数
【发布时间】:2020-05-14 10:55:44
【问题描述】:

我想从一个json数组中找出最大值

JSON:

[
    {
        "item_id": "129",
        "item_name": "HP Leserjet",
        "item_quantity": "10",
        "item_rate": "80000.75",
        "item_purchase_date": "2020-05-13T00:00:00Z"
    },
    {
        "item_id": "130",
        "item_name": "HP Leserjet",
        "item_quantity": "10",
        "item_rate": "80000.75",
        "item_purchase_date": "2020-05-13T00:00:00Z"
    },
    {
        "item_id": "131",
        "item_name": "HP Leserjet",
        "item_quantity": "10",
        "item_rate": "80000.75",
        "item_purchase_date": "2020-05-13T00:00:00Z"
    }
]

让我们说这个长 json 保存在一个名为 posts 的变量中。我必须使用 for of 循环(因为我在 typescript 内)。 [我希望它可以是一个简单的 c 循环]

无论如何,这就是我的尝试。我需要找到最大的 item_id 。我不知道为什么它不起作用

file.ts

  makeMaxId()
  { let x = 0;
    for (let post of this.posts) {
      if (post[0] > x)
      {
        x = this.post[0];
      }
    }
    console.log(x);
  }

【问题讨论】:

  • 您只想要最大的 item_id 还是整个对象?
  • 哪个字段的最大值?在您的代码中,post 包含对数组中每个对象的引用,其他任何地方都没有,并且您的对象没有键为“0”的字段。因此,当您引用 post[0] 时,您总是会得到 undefined
  • @VikasKeskar 是的
  • @keskinsaf 最大 item_id ,所以我的意思是第一个索引,索引 [0]
  • 然后试试: ... post['item_id'] > x ...

标签: javascript json typescript


【解决方案1】:

以下语句将为您提供最大 item_id

Math.max(...this.posts.map(p => Number(p.item_id)))

【讨论】:

    【解决方案2】:
     makeMaxId(){
        let x = 0;
        for (let post of this.posts) {
          if (post['item_id'] > x)
          {
            x = post['item_id'];
          }
        }
        console.log(x);
      }
    

    【讨论】:

      【解决方案3】:
      let B= A.map(item =>parseInt(item.item_id));
      console.log(Math.max(...B));
      

      【讨论】:

      • 感谢您提供此代码 sn-p,它可能会提供一些有限的即时帮助。 proper explanation 将通过展示为什么这是解决问题的好方法,并使其对有其他类似问题的未来读者更有用,从而大大提高其长期价值。请edit您的回答添加一些解释,包括您所做的假设。
      【解决方案4】:

      怎么样

      const mySortedPosts = this.posts.sort((a, b) => {
        return Number(b.item_id) - Number(a.item_id)
      })
      
      mySortedPosts[0] // <-- post with greatest item_id
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-21
        • 1970-01-01
        相关资源
        最近更新 更多