在Angular中将JSON值从String转换为Integer

时间:2016-11-03 13:01:53

标签: angularjs json

我有一个非常大的JSON对象数组(大约4000个对象)。其中一个键的值是一个字符串,我想将它转换为一个整数,所以我可以迭代数组并拉出具有该键的最大值的对象。以下是数组的示例:

[
  {
    "id": "34567",
    "title": "Some title",
    "likes": "5",
    "comments": "7",
    "views": "3"
  },
  {
    "id": "34568",
    "title": "Some title 2",
    "likes": "4",
    "comments": "7",
    "views": "3"
  },
  {
    "id": "34569",
    "title": "Some title 3",
    "likes": "3",
    "comments": "7",
    "views": "3"
  },
  {
    "id": "34560",
    "title": "Some title 4",
    "likes": "2",
    "comments": "7",
    "views": "3"
  }
]

我尝试做的是迭代数组,转换“喜欢”的数据。将值转换为整数,然后拉出具有最大值的对象,用于'喜欢'。

2 个答案:

答案 0 :(得分:2)

这只是简单的javascript,做这样的事情:

if (myArray.length) {

    var heighest = myArray[0];
    for (var i = 1; i < myArray.length; i++) {
        var likes = parseInt(myArray[i].likes);
        if (likes > heighest.likes) {
            heighest = myArray[i];
        }
    }

    console.log(heighest); // logs object with id 34567
} else {
    console.log("No items in array");
}

答案 1 :(得分:0)

检查此解决方案。将likes值存储在临时变量中,如果通过将当前对象替换为更高的值,则替换它。

&#13;
&#13;
var items = [{
  "id": "34567",
  "title": "Some title",
  "likes": "5",
  "comments": "7",
  "views": "3"
}, {
  "id": "34568",
  "title": "Some title 2",
  "likes": "4",
  "comments": "7",
  "views": "3"
}, {
  "id": "34569",
  "title": "Some title 3",
  "likes": "3",
  "comments": "7",
  "views": "3"
}, {
  "id": "34560",
  "title": "Some title 4",
  "likes": "2",
  "comments": "7",
  "views": "3"
}];

var best;
var max = 0;
for (var i = 0; i < items.length; i++) {
  var likes = parseInt(items[i].likes);
  if (likes > max) {
    max = likes;
    best = items[i];
  }
}

console.log(best);
&#13;
&#13;
&#13;