我有一个数组
var arrList = [{
"email": "a@mailinator.com",
"pname": "john doe1" },
{
"email": "a@mailinator.com",
"pname": "john doe2" },
{
"email": "a@mailinator.com",
"pname": "john doe3" } ]
Run Code Online (Sandbox Code Playgroud)
我想转换这个数组,并希望输出如下
{
"a@mailinator.com": [{
"email": "a@mailinator.com",
"pname": ["john doe1", "john doe2", "john doe3"]
}]
}
Run Code Online (Sandbox Code Playgroud)
我在下面尝试了lodash但没有成功
arrList = _.uniqBy(arrList, "email", "pname")
result = _.chain(arrList).groupBy('email').value('')
Run Code Online (Sandbox Code Playgroud)
在数组中,有多个不同的电子邮件呈现,我们需要按电子邮件分组。
使用_.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);Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2258 次 |
| 最近记录: |