AngularJS:如何从JSON响应创建新数组?

时间:2016-07-15 18:04:00

标签: arrays angularjs json

我的控制器上有一个与工厂绑定的功能:

fac.GetDailyCountersList = function () {
    return $http.get('/Data/GetDailyCountersList')
}

在控制器内部,这里是调用函​​数的地方:

$scope.DailyCounters = null;
DailyCounterService.GetDailyCountersList().then(function (d) {
    $scope.DailyCounters = d.data;
}, function (error) {
    alert('Error!');
});

基于此,如果我要在html页面上输出变量,则会显示:

[{"Id":1,"MIDay":"16","MITime":"900","MICounter":0},
{"Id":2,"MIDay":"16","MITime":"915","MICounter":1},
{"Id":3,"MIDay":"16","MITime":"930","MICounter":0},
{"Id":4,"MIDay":"17","MITime":"945","MICounter":0},
{"Id":5,"MIDay":"17","MITime":"1000","MICounter":0},
{"Id":6,"MIDay":"17","MITime":"1015","MICounter":52},
{"Id":7,"MIDay":"18","MITime":"1030","MICounter":2},
{"Id":8,"MIDay":"18","MITime":"1045","MICounter":3},
{"Id":9,"MIDay":"18","MITime":"1100","MICounter":0}]

我的问题是如何根据Json数据的一个属性获取此数据并创建其他数组。

例如,我如何放置数组

{"Id":1,"MIDay":"16","MITime":"900","MICounter":0},
{"Id":2,"MIDay":"16","MITime":"915","MICounter":1},
{"Id":3,"MIDay":"16","MITime":"930","MICounter":0}

进入新阵列“ArrayDay16”?其余的也进入各自的阵列。

我正在考虑这样做:

var myArray = [];
if (d.data['MIDay'] == '16')
    myArray.push(d.data);

但这不正确/失败。有效解决方案的想法吗?

4 个答案:

答案 0 :(得分:0)

使用filter函数填充新数组。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

//This will populate "someArray" with only the data that has MIDAY = 16
DailyCounterService.GetDailyCountersList().then(function (d) {
    $scope.someArray = d.data.filter(function(ele) {
        return ele.MIDAY === '16';
    });
}

答案 1 :(得分:0)

您可以使用filter功能:

var daySixteen = data.filter(function (d) { return d.MIDay === "16"; });

答案 2 :(得分:0)

你可以尝试下一个:

d.data.foreach(function(item){
    if(item.MIDay == 16)
        myArray.push(d.data);
});

答案 3 :(得分:0)

如果你想要有效率,你应该在后端用约束做这个。这不是浏览器的工作。

虽然,如果你仍然希望它在前端过滤它,你可以使用带有一些lamdba表达式的filter-function

var newList = oldList.filter(i => i["MIDay"] == "16");