我可以在前端安装我的数据,但我需要做一些逻辑来组织这些数据,我不确定这类问题的最佳方法是什么。我需要对每个项目的分析数量进行“计数”。因此,每个对象下面都有一个project_id和一个analysis_id。因此必须有一种方法来为每个对象创建一个计数变量,用javascript表示每个项目有多少分析。非常感谢任何帮助。
答案 0 :(得分:0)
你可以这样做。为迭代的每个对象创建一个对象,检查是否有该project_id的现有属性。如果没有将其初始化为0.则向其中添加1。
select partition,
<calculation>,
...
from
(
select ...
from SomeEntity sm
cross join (
select 'June' as [partition] 20140601 as [start], 20140630 as [end] union all
'July', 20140701, 20140731 union all,
'Sommar', 20140601, 20150828
) as cons
....
where sm.SomeProp >= cons.[start] and sm.SomeProp <= cons.[end]
)
group by partition
....
小提琴:http://jsfiddle.net/Lbohgnxs/
编辑:因此,如果您希望对每个对象进行这些计数,您只需设置每次迭代的计数即可。因为对象只是对内存中某个点的引用,所以每个引用在循环完成后都会有最终值。
小提琴:http://jsfiddle.net/Lbohgnxs/1/
var projectCounts = {}, index = 0; length = someData.length;
for ( ; index < length; index++) {
var projectId = someData[index].project_id;
if (!projectCounts['Project' + projectId]) {
projectCounts['Project' + projectId] = 0;
}
projectCounts['Project' + projectId]++
}
如果您不喜欢每次计数并只想要特定的项目计数,您可以创建一个计数对象并使用该参考。
小提琴:http://jsfiddle.net/Lbohgnxs/2/
var projectCounts = {}, index = 0; length = someData.length;
for ( ; index < length; index++) {
var projectId = someData[index].project_id;
if (!projectCounts['Project' + projectId]) {
projectCounts['Project' + projectId] = 0;
}
projectCounts['Project' + projectId]++
someData[index].counts = projectCounts;
}
答案 1 :(得分:0)
您可以循环数组并更新将项目ID映射到其计数的对象:
// simplified sample data
var analyses = [
{
project_id: 1,
analysis_id: 10
},
{
project_id: 2,
analysis_id: 11
},
{
project_id: 3,
analysis_id: 12
},
{
project_id: 3,
analysis_id: 13
}
];
var counts = {};
analyses.forEach( function(el) {
var pid = el.project_id;
counts[pid] = counts[pid] || 0; // start at 0 if we haven't seen this project before
++counts[pid];
});
console.log(counts); // {1: 1, 2: 1, 3: 2