gpt4 book ai didi

node.js - 使用 lodash 分组数组

转载 作者:搜寻专家 更新时间:2023-11-01 00:16:24 25 4
gpt4 key购买 nike

我有一个数组

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('')

在多个不同的邮件呈现数组中,我们需要按邮件分组。

最佳答案

使用_.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>

关于node.js - 使用 lodash 分组数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49511568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com