javascript - 检查数组中是否存在键

标签 javascript json

我目前在从数组中获取不同的值列表时遇到一些问题。

我正在寻找的是能够以表格形式提供离散值计数的东西

我有以下项目数组

[{"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":"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 提供了一个项目。

最佳答案

看起来您需要一个字典或哈希来创建唯一办公室的列表,然后将其转换为最终结果的数组。

在您的代码中,您将数组语法与关联数组(文字对象)语法混淆了。

差异示例:

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]);

关于javascript - 检查数组中是否存在键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17323787/

相关文章:

javascript - Flow 无法理解对 null 或未定义的检查

javascript - 为什么JS代码不起作用?

json - 使用 Spray-json 在 SCALA 中解析复杂的 JSON

javascript - 我如何解析此 JSON 以便在 Backbone View 中使用

javascript - c3 图表工具提示不移动

javascript - jQuery Datepicker 触发 POST

javascript - 将字段推送到对象数组的每个元素(MongoDB)

json - Spring Data JPA @OneToMany 无限循环异常

c# - Json.NET 可以反序列化 "dynamic"属性吗?

javascript - 如何使用 php mysql json 根据 url 中的行 id 从数据库检索值?