如何使用Angular.js或Javascript根据键值测量Json数组长度

时间:2016-03-03 07:24:32

标签: javascript angularjs json

我需要帮助。我需要使用Angular.js或Javascript来测量基于键值的json数组长度。我正在解释下面的代码。

[{"day_id":"1","b":"sss"},
  {"day_id":"2","b":"ffff"},
  {"day_id":"3","b":"ccc"},
  {"day_id":"3","b":"hhh"},
{"day_id":"4","b":"kkk"}]

在这里,我需要测量day_id=3 or 2 etcday_id=3中存在多少数据集的长度,此处有3个数据存在2组。请帮助我。

6 个答案:

答案 0 :(得分:1)

这可以帮到你。

function filterData(data, key, val){
   var result = [];
   for(var i=0;i< data.length; i++){
      if ((data[i][key]) && (data[i][key] == val)) {
         result.push(data[i]);
      }
   }
   return result;
}

您可以将其用作filterData(data, "day_id", 3)

免责声明:可能有错别字。

答案 1 :(得分:1)

此解决方案使用角度。

// data is your array
function MyCtrl($scope, $filter) {
  $scope.data = [{
    "day_id": "1",
    "b": "sss"
  }, {
    "day_id": "2",
    "b": "ffff"
  }, {
    "day_id": "3",
    "b": "ccc"
  }, {
    "day_id": "3",
    "b": "hhh"
  }, {
    "day_id": "4",
    "b": "kkk"
  }];
  $scope.count = $filter('filter')($scope.data, {
    day_id: 1
  }).length;
}
<!DOCTYPE html>
<html ng-app>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>

<body ng-controller="MyCtrl">
  Count: {{count}}
</body>

</html>

答案 2 :(得分:1)

你可以试试这个:

istore_<n>

demo

答案 3 :(得分:1)

这是一个更通用的解决方案,它需要一个具有搜索属性的对象和值。

迭代数组并计算所需属性是否具有相同的值。

&#13;
&#13;
function getCount(array, search) {
    var c = 0,
        k = Object.keys(search)[0];

    array.forEach(function (a) {
        a[k] === search[k] && c++;
    });
    return c;
}

var array = [{ "day_id": "1", "b": "sss" }, { "day_id": "2", "b": "ffff" }, { "day_id": "3", "b": "ccc" }, { "day_id": "3", "b": "hhh" }, { "day_id": "4", "b": "kkk" }];
document.write(getCount(array, { day_id: '2' }) + '<br>');
document.write(getCount(array, { day_id: '3' }) + '<br>');
&#13;
&#13;
&#13;

答案 4 :(得分:1)

您可以使用 Array.prototype.filter 方法:

var filtered_array = your_array.filter(function(row) {
    return row.day_id = "3"
});

var day_id_count = filtered_array.length

答案 5 :(得分:0)

试试这个。你可以在数组上使用过滤功能

var arr = [{
  "day_id": "1",
  "b": "sss"
}, {
  "day_id": "2",
  "b": "ffff"
}, {
  "day_id": "3",
  "b": "ccc"
}, {
  "day_id": "3",
  "b": "hhh"
}, {
  "day_id": "4",
  "b": "kkk"
}]

Array.prototype.findCountByPropertyValue=function(property_name,value)
{
  return arr.filter(function(i) { return i[property_name] == value}).length
}
document.write(arr.findCountByPropertyValue('day_id',1))
document.write('<br>')
document.write(arr.findCountByPropertyValue('day_id',2))
document.write('<br>')
document.write(arr.findCountByPropertyValue('day_id',3))
document.write('<br>')
document.write(arr.findCountByPropertyValue('day_id',4))
document.write('<br>')
document.write(arr.findCountByPropertyValue('day_id',5))