检查数组中是否存在密钥

Qpi*_*ate 0 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}]
Run Code Online (Sandbox Code Playgroud)

我正在寻找以下输出,这是一个不同的办事处清单,每个办事处的实例数量.

[
    {"office":"abc","count":1},
    {"office":"def","count":2},
    {"office":"ghi","count":1}
]
Run Code Online (Sandbox Code Playgroud)

以下我试过的是

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;
    }
});
Run Code Online (Sandbox Code Playgroud)

但这给了我Office原始数组中每个项目的单个项目.

Jos*_*ell 6

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

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

差异示例:

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
Run Code Online (Sandbox Code Playgroud)

要修复您的代码:

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]);
Run Code Online (Sandbox Code Playgroud)