从键值最低的JSON数组中获取数组

时间:2019-03-11 09:42:56

标签: javascript typescript

在如下所示的数组中:

[{
    "sport" : "Cricket",
    "score" : "22.45"
},
{
    "sport" : "Tennis",
    "score" : "-12"
}]

我想迭代JSON并找到得分最低的数组。在这种情况下,获取

{
    "sport" : "Tennis",
    "score" : "-12"
}

4 个答案:

答案 0 :(得分:1)

根据得分升序排列并返回第一个对象

var a = [{
    "sport": "Cricket",
    "score": "22.45"
  },
  {
    "sport": "Tennis",
    "score": "-12"
  }
];
console.log(a.sort((a, b) => a.score - b.score)[0])

答案 1 :(得分:0)

尝试使用此方法从具有最低键值的JSON数组获取数组

let myArray =[{
    "sport" : "Cricket",
    "score" : "22.45"
},
{
    "sport" : "Tennis",
    "score" : "-12"
},
{ "sport" : "Tennis", "score" : "-12000" }]

let minOfArray =myArray.reduce(function(prev, curr) {
    return parseInt(prev.score) < parseInt(curr.score) ? prev : curr;
});

console.log(minOfArray);

答案 2 :(得分:0)

您应该使用parseInt

var arr = [{
    "sport" : "Cricket",
    "score" : "22.45"
},
{
    "sport" : "Tennis",
    "score" : "-12"
},
{
    "sport" : "Tennis",
    "score" : "-12000"
}];

var res = arr.reduce((a,c) => parseInt(c.score) < parseInt(a.score) ? c : a);

答案 3 :(得分:0)

您可以使用reduce遍历您的商品并获得最低分:

const data = [{
  "sport" : "Cricket",
  "score" : "22.45"
}, {
  "sport" : "Tennis",
  "score" : "-12"
}];

const result = data.reduce((acc, x) => x.score < acc.score ? x : acc, data[0]);

console.log(result);