我目前在从数组中获取不同的值列表时遇到一些问题。
我正在寻找的是能够在表单中给出distict值计数的东西
我有以下项目数组
[{"Office":"abc", "Name":"ABC", "Total":0},
{"Office":"def", "Name":"DEF", "Total":11},
{"Office":"def", "Name":"DEF", "Total":1},
{"Office":"ghi", "Name":"GHI", "Total":1111}]
我正在寻找以下输出,这是一个不同的Office列表,其中包含每个Office的实例数。
[
{"office":"abc","count":1},
{"office":"def","count":2},
{"office":"ghi","count":1}
]
下面是我尝试过的
ko.utils.arrayForEach(officeLines, function (item, indx)
{
var office = item.Office;
if (test[office] == null)
{
test.push({ office: office, count: 1 });
}
else
{
test["office"][office] += 1;
}
});
但这为原始数组中的每个Office
提供了一个单独的项。
发布于 2013-06-26 23:17:03
看起来您需要一个字典或散列来创建唯一办公室的列表,然后将其转换为最终结果的数组。
在您的代码中,您混淆了数组语法和关联数组(文本对象)语法。
差异示例:
var array = [];
array[0] = { bar: 'foo' }; // note the numeric index accessor/mutator
var obj = {};
obj['property'] = { bar: 'foo' }; // the brackets serve as a property accessor/mutator
修复代码的:
var hash = {}; // object literal
ko.utils.arrayForEach(officeLines, function (item, indx) {
var office = item.Office;
if (!hash.hasOwnProperty(office)) {
hash[office] = { office: office, count: 1 };
}
else {
hash[office].count++;
}
});
// make array
var test = [];
for(var office in hash)
if(hash.hasOwnProperty(office))
test.push(hash[office]);
发布于 2013-06-26 23:27:20
您似乎在这里混合了数组和对象。
if (test[office] == null)
将测试数组 test
是否具有属性abc
、def
等。此条件将始终为真,因为数组没有这些属性。您通常将具有数字属性的属性添加到数组中,例如,您也可以使用.push
。
另一方面,对象可以具有任意属性。
现在关于:
test["office"][office] += 1;
这将访问数组的属性office
(该属性不存在),然后访问属性abc
、def
等(这些属性当然也不存在,因为test.office
本来就不存在)。
你必须决定你希望test
是一个数组还是一个对象。
如果您选择一个对象,则聚合数据将更容易,因为您可以轻松地测试对象属性的存在。
如果需要数组,可以将对象转换为数组,或者如果从一开始就使用数组,则必须遍历数组的元素并找到正确的元素。这种解决方案不太可取,因为运行时将是O(n^2)
。
对象:
var test = {};
ko.utils.arrayForEach(officeLines, function (item, indx) {
var office = item.Office;
if (!test[office]) {
hash[office] = 1
}
else {
hash[office] += 1;
}
});
然后,test
将如下所示:
{
abc: 1,
def: 2,
ghi: 1
}
从你想要的数组中创建一个数组是很容易的。
数组:
var test = [];
ko.utils.arrayForEach(officeLines, function (item, indx) {
var office = item.Office;
for (var i = 0, l = test.length; i < l; i++) {
if (test[i].office === office) {
test[i].count += 1;
return;
}
}
test.push({office: office, count: 1});
});
我希望您已经从嵌套循环(forEach
中的for
)中看到,这不是一个最佳解决方案。
进一步阅读材料:
发布于 2013-06-26 23:15:13
像这样的怎么样?
var test = {};
ko.utils.arrayForEach(officeLines, function (item, indx)
{
var office = item.Office;
if (typeof test[office] === "undefined")
{
test[office] = 1;
}
else
{
test[office]++;
}
});
// back to array
var array = [];
for (var office in test) {
array.push({ office: office, count: test[propertyName] });
}
我认为您可能不必转换回数组,因为您可以使用$index获取办公室名称,然后在knockoutjs中使用$data作为foreach中的计数。
https://stackoverflow.com/questions/17323787
复制相似问题