[英]Count number of items in an array of objects with a specific property value (JavaScript)
I have an array of objects. 我有一个对象数组。 Note that "created" sometimes has the same value more than once.
请注意,“创建的”有时具有相同的值不止一次。 Also note that "status" is sometimes "0":
另请注意,“状态”有时为“ 0”:
var array = [
{"created":"Jan 1","status":1},
{"created":"Jan 1","status":1},
{"created":"Jan 2","status":1},
{"created":"Jan 3","status":0},
{"created":"Jan 4","status":1},
{"created":"Jan 4","status":1}
];
I want a new a new array of objects like this: 我想要一个新的对象数组,如下所示:
var newArrayA = [
{"Jan 1":2},
{"Jan 2":1},
{"Jan 3":0},
{"Jan 4":2}
];
OR a multidimensional array like this (I'm not sure which is better for D3.js): 或像这样的多维数组(我不确定哪个更适合D3.js):
var newArrayB = [
["Jan 1",2],
["Jan 2",1],
["Jan 3",0],
["Jan 4",2]
];
So, when "status" is "1", it counts the number of "created" that are the same. 因此,当“状态”为“ 1”时,它将计算相同的“创建”数。 And when status is "0", that is also included.
当状态为“ 0”时,也包括在内。
How do I do this? 我该怎么做呢? Here's what I have so far JSFIDDLE .
到目前为止,这是我的JSFIDDLE 。 Is this how to approach it?
请问这是怎么处理的? Or am I missing some simple solution?
还是我缺少一些简单的解决方案? Thanks!
谢谢!
D3 would cope with either result format - it does slightly depend on what you want to do with it. D3可以处理任何一种结果格式-它确实取决于您要使用的格式。 Regardless, here is some example code for generating either format:
无论如何,以下是一些生成两种格式的示例代码:
var result = {};
array.forEach(function(i) {
if (!result.hasOwnProperty(i.created)) {
result[i.created] = 0;
}
if (i.status === 1) {
result[i.created] += 1;
}
});
var newArrayA = Object.keys(result)
.map(function(k) {
var o={};
o[k] = result[k];
return o;
})
var newArrayB = Object.keys(result)
.map(function(k) { return [k,result[k]] })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.