我有一个数组
var arrList = [{
"email": "a@mailinator.com",
"pname": "john doe1" },
{
"email": "a@mailinator.com",
"pname": "john doe2" },
{
"email": "a@mailinator.com",
"pname": "john doe3" } ]
我想转换这个数组,并希望输出如下
{
"a@mailinator.com": [{
"email": "a@mailinator.com",
"pname": ["john doe1", "john doe2", "john doe3"]
}]
}
我已尝试使用lodash但未成功
arrList = _.uniqBy(arrList, "email", "pname")
result = _.chain(arrList).groupBy('email').value('')
在阵列中有多个不同的电子邮件,我们需要通过电子邮件进行分组。
答案 0 :(得分:3)
使用_.groupBy()
,然后_.map()
将分组对象添加到请求的表单中:
var arrList = [{"email":"a@mailinator.com","pname":"john doe1"},{"email":"a@mailinator.com","pname":"john doe2"},{"email":"a@mailinator.com","pname":"john doe3"}];
var result = _(arrList)
.groupBy('email')
.map((v, email) => ({
email,
pname: _.map(v, 'pname')
}))
.value();
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
答案 1 :(得分:1)
您可以使用_.chain
和_.groupBy
并根据您的要求创建数组。
var arrList = [{
"email": "a@mailinator.com",
"pname": "john doe1" },
{
"email": "a@mailinator.com",
"pname": "john doe2" },
{
"email": "a@mailinator.com",
"pname": "john doe3" },
{
"email": "b@mailinator.com",
"pname": "b doe2" },
{
"email": "b@mailinator.com",
"pname": "b doe3" }]
var result=_.chain(arrList).groupBy("email").map(function(v, i) {
return {
email: i,
pname: _.map(v, 'pname')
}
}).value();
document.body.innerHTML = '<pre>' + JSON.stringify(result, null, ' ') + '</pre>';
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js"></script>
&#13;
请运行以上代码段
答案 2 :(得分:0)
如果你想使用核心js解决方案,那么试试这个
var arrList = [{
"email": "a@mailinator.com",
"pname": "john doe1" },
{
"email": "a@mailinator.com",
"pname": "john doe2" },
{
"email": "a@mailinator.com",
"pname": "john doe3" } ]
var temp = {};
for(var value of arrList){
temp[value.email] = temp[value.email] || [];
temp[value.email][0] = temp[value.email][0] || {};
temp[value.email][0].pname = temp[value.email][0].pname || [];
temp[value.email][0].email = value.email;
temp[value.email][0].pname.push(value.pname);
}
console.log(JSON.stringify(temp));