gpt4 book ai didi

javascript - Lodash 按字母表分组

转载 作者:行者123 更新时间:2023-11-28 12:15:27 25 4
gpt4 key购买 nike

我正在处理一个包含一些用户详细信息的对象,我需要将该对象转换为另一个对象以构建联系人应用程序。我正在使用 Lodash 处理数组和对象。

[
{
"id": 1,
"first_name": "Alie",
"last_name": "Stigger",
"email": "astigger0@lulu.com",
"gender": "Female",
"avatar":
"https://robohash.org/sintnihiladipisci.jpg?size=200x200&set=set1",
"phone_number": "617-845-6906"
},
{
"id": 2,
"first_name": "Kendall",
"last_name": "Mayes",
"email": "kmayes1@bbb.org",
"gender": "Male",
"avatar": "https://robohash.org/nemoetqui.jpg?size=200x200&set=set1",
"phone_number": "193-270-2893"
},
{
"id": 3,
"first_name": "Yolanthe",
"last_name": "Maddaford",
"email": "ymaddaford2@reference.com",
"gender": "Female",
"avatar":
"https://robohash.org/exercitationemestaccusamus.jpg?size=200x200&set=set1",
"phone_number": "267-365-2165"
}
]

现在我想要的只是使用 Lodash 从主对象构建另一个对象,其中包含基于 last_name 属性的字母。

在这种情况下:

[
{
letter: "S",
contacts: [
{
id: 1,
first_name: "Alie",
last_name: "Stigger",
email: "astigger0@lulu.com",
gender: "Female",
avatar:
"https://robohash.org/sintnihiladipisci.jpg?size=200x200&set=set1",
phone_number: "617-845-6906"
}
]
},
{
letter: "M",
contacts: [
{
id: 2,
first_name: "Kendall",
last_name: "Mayes",
email: "kmayes1@bbb.org",
gender: "Male",
avatar: "https://robohash.org/nemoetqui.jpg?size=200x200&set=set1",
phone_number: "193-270-2893"
},
{
id: 3,
first_name: "Yolanthe",
last_name: "Maddaford",
email: "ymaddaford2@reference.com",
gender: "Female",
avatar:
"https://robohash.org/exercitationemestaccusamus.jpg?size=200x200&set=set1",
phone_number: "267-365-2165"
}
]
}
]

最佳答案

您可以按大写值进行分组,然后映射结果。

var data = [{ id: 1, first_name: "Alie", last_name: "Stigger", email: "astigger0@lulu.com", gender: "Female", avatar: "https://robohash.org/sintnihiladipisci.jpg?size=200x200&set=set1", phone_number: "617-845-6906" }, { id: 2, first_name: "Kendall", last_name: "Mayes", email: "kmayes1@bbb.org", gender: "Male", avatar: "https://robohash.org/nemoetqui.jpg?size=200x200&set=set1", phone_number: "193-270-2893" }, { id: 3, first_name: "Yolanthe", last_name: "Maddaford", email: "ymaddaford2@reference.com", gender: "Female", avatar: "https://robohash.org/exercitationemestaccusamus.jpg?size=200x200&set=set1", phone_number: "267-365-2165" }],
result = _(data)
.groupBy(o => o.last_name[0].toUpperCase())
.map((contacts, letter) => ({ letter, contacts }))
.value();

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

关于javascript - Lodash 按字母表分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50664773/

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