我需要帮助。我需要使用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 etc
在day_id=3
中存在多少数据集的长度,此处有3个数据存在2组。请帮助我。
答案 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)
答案 3 :(得分:1)
这是一个更通用的解决方案,它需要一个具有搜索属性的对象和值。
迭代数组并计算所需属性是否具有相同的值。
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;
答案 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))