【发布时间】: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