如何使用JAVASCRIPT通过电子邮件区分json数组

时间:2018-03-15 11:37:35

标签: javascript arrays json

如何使用javascript按值区分JSON数组。下面是我的JSON数组。我想计算不同元素的大小。

 [
       {
                "_id": "5aaa4f8cd0ccf521304dc6bd",
                "email": "srjahir32@gmail.com"
            },
            {
                "_id": "5aaa50a0ac40d32404c8bab7",
                "email": "srjahir32@gmail.com",
            },
            {
                "_id": "5aa8ace3323eeb001414a2c5",
                "email": "g.anshul@gmail.com"
            },
            {
                "_id": "5aa86645323eeb001414a2af",
                "email": "bspilak@cooperequipment.ca"

            },
            {
                "_id": "5aa92c7d66c8820014813ed8",
                "email": "g.anshul@gmail.com"
            }
    ]

预期结果应为3。

2 个答案:

答案 0 :(得分:0)

您可以使用lodash https://lodash.com/docs/4.17.5#groupBy的groupBy方法,然后获取结果数组的长度

答案 1 :(得分:0)

您可以使用reduce功能。

此备选方案存储以前的电子邮件以增加计数。

var array = [{    "_id": "5aaa4f8cd0ccf521304dc6bd",    "email": "srjahir32@gmail.com"  },  {    "_id": "5aaa50a0ac40d32404c8bab7",    "email": "srjahir32@gmail.com",  },  {    "_id": "5aa8ace3323eeb001414a2c5",    "email": "g.anshul@gmail.com"  },  {    "_id": "5aa86645323eeb001414a2af",    "email": "bspilak@cooperequipment.ca"  },  {    "_id": "5aa92c7d66c8820014813ed8",    "email": "g.anshul@gmail.com"  }];

var count = array.reduce((a, c) => {
  if (!a[c.email]) a[c.email] = ++a.count;
  return a;
}, {count: 0}).count;

console.log(count);

使用对象Set

  • 映射到电子邮件数组。
  • 使用该映射数组初始化对象Set。
  • 使用属性count获取size

var array = [{    "_id": "5aaa4f8cd0ccf521304dc6bd",    "email": "srjahir32@gmail.com"  },  {    "_id": "5aaa50a0ac40d32404c8bab7",    "email": "srjahir32@gmail.com",  },  {    "_id": "5aa8ace3323eeb001414a2c5",    "email": "g.anshul@gmail.com"  },  {    "_id": "5aa86645323eeb001414a2af",    "email": "bspilak@cooperequipment.ca"  },  {    "_id": "5aa92c7d66c8820014813ed8",    "email": "g.anshul@gmail.com"  }],
    mapped = array.map(e => e.email),
    set = new Set(mapped),
    count = set.size;

console.log(count);