JavaScript - 使用es6计算并移除对象数组中的重复项

3
我是一个帮助翻译文本的助手。

我正在尝试修复这个问题,但我有些困惑,需要一些帮助和建议。我试图越来越了解es6,但我不知道最好的方法来解决我的问题。

我正在获取一个大的json文件,它看起来有点像这样:

[
    {
        "company": "Google",
        "location": "USA",
        "email": null
    },
    {
        "company": "Microsoft",
        "location": "USA",
        "email": "mail@mail.com"
    },
    {
        "company": "Google",
        "location": "NLD",
        "email": "mail@mail.com"
    }
]

我会在表格中展示这些数据,想要添加复选框筛选器,同时也想在旁边添加计数,如下:

[x] Google (2)
[ ] Microsoft (1)
// other function call
[ ] mail@mail.com (2)

我有一个函数,我每次调用它都会传入三个参数(公司、地点、邮箱):

function filterArr(data, key) {

    data.forEach(element => {

        let countedData = data.filter((el) => {
            return el[key] == element[key]
        }).length;
// console.log(element[key] + ": " + countedData);
    });

    data = data.filter((item, index, self) => self.findIndex( t => t[key] === item[key] && item[key] != null) === index )
// console.log(data)
    return data;
}

filterArr(data, "company");

我尝试使用上述函数输出以下内容: Google: 2 Microsoft: 1
foreach 函数正确地计算了键值,但是显然记录了以下内容: Google: 2 Microsoft: 1 Google: 2
filter console.log 显示了 Google 和 Microsoft(只显示一次,就像我想要的那样 :)
现在我需要将这两个函数组合起来,但我不确定如何以及最佳方式是什么(请参见我的 fiddle:https://jsfiddle.net/z359qo1d/
你知道下一步该怎么做吗?
2个回答

7
Array.prototype.reduce 是你想要的完美选择。
function filterArr(data, key){
  return data.reduce( (result, current) => {
    if(!result[current[key]]){
      result[current[key]] = 1;
    } else {
      result[current[key]] += 1;
    }
    return result;    
  }, {})
}

上述代码将返回以下对象
{
  Google: 2,
  Microsoft: 1
}

我最喜欢的答案。将 if(!result[current[key]]) 替换为 if(! (current[key] in result) ),否则计数器可能永远不会增加... - RaphaMex
@RaphaMex 指出得好。更新后我将其初始化为1而不是0。 - eltonkamami
谢谢!非常好用,我差点自己找到了解决方案,但这个非常棒!! - elDrimm

1
我会稍微有所不同地做:

let _in = [
{
    "company": "Google",
    "location": "USA",
    "email": null
},
{
    "company": "Microsoft",
    "location": "USA",
    "email": "mail@mail.com"
},
{
    "company": "Google",
    "location": "NLD",
    "email": "mail@mail.com"
}
]

function countEm(accum, each) {
  if (! accum[each.company] )
    accum[each.company] = 0
  accum[each.company] += 1
  return accum
}

console.log(_in.reduce(countEm, {}))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接