【发布时间】:2018-06-15 20:41:03
【问题描述】:
在 Angular 组件上的页面加载时,我执行如下获取请求:
private getData() {
const url = 'http...';
const data= this.http.get(url).map( res => res.json());
return data;
}
我得到了这个结果:
[
{
id: 1,
type: "science",
action: "on",
name: "title 1",
frequency: 10,
author: null,
},
{
id: 3,
type: "thriller",
action: "off",
name: "Programming",
frequency: 60,
author: 1515202398191,
},
{
id: 4,
type: "article",
action: "pause",
name: "Stories about life",
frequency: 60,
author: 1515202398191,
},
{
id: 5,
type: "science",
action: "on",
name: "Lorem Ipsum",
frequency: 60,
author: 1515202398191,
},
{
id: 6,
type: "science",
action: "off",
name: "Testing",
frequency: 60,
author: 1515202398191,
},
{
id: 8,
type: "science",
action: "on",
name: "Programming",
frequency: 60,
author: 1515202398191,
}
]
在数组里面我有不同的项目,它们都有 type 和 action 有值。我想计算type 和action 具有相同值的项目,这样我就可以获得一些统计数据,例如:
[{"type":"science", action:"on", count: 3},
{"type":"science", action:"off", count: 1},
{"type":"thriller", action:"off", count: 1},
{"type":"article", action:"pause", count: 1},
]
我开始做某事,但我不知道该怎么做
stats: any;
function countArr(array){
var array= [];
var count = 0;
array.forEach( function(currentItem){
array.forEach( function(item){
// check if
if(item.type == currentItem.type && item.action == currentItem.action){
count++;
}
});
var itemJson = {'type':currentItem.type, 'action':currentItem.action, 'count':count };
array.push(itemJson);
});
}
private getData() {
const url = 'http...';
const data= this.http.get(path).map( res => res.json());
this.stats = countArr(data);
return data;
}
【问题讨论】:
-
使用 reduce/find 组合很容易做到 - 但是您如何期望
{"type":"thriller", action:"on", count: 0},...您如何计算输入中没有的内容?例如jsfiddle.net/Lg54er4z/1 -
我更新了预期的数组,所以基本上我删除了它
-
啊,没看到修改后的版本:p
标签: javascript angularjs json typescript