gpt4 book ai didi

javascript - Lodash:用值对象内部属性交换键

转载 作者:行者123 更新时间:2023-11-28 14:31:47 24 4
gpt4 key购买 nike

我收到以下 JSON 响应:

users: {
1: {
name: "John",
email: "john@test.com",
id: 1,
place: "NY"
},
2: {
name: "Alex",
email: "alex@test.com",
id: 2,
place: "FL"
},
3: {
name: "Tony",
email: "tony@test.com",
id: 3,
place: "TX"
}
.
.
.
.
.
.
}

我想将内部对象值中的 id 键与电子邮件键交换,如下格式。

users: {
"john@test.com": {
name: "John",
email: "john@test.com",
id: 1,
place: "NY"
},
}

我正在使用下面的 lodash 代码来使其工作并且工作正常:

_.keyBy(_.values(data), 'email');

有没有更好的方法可以用 lodash 处理它?我是 lodash 的新手,我想了解代码是否可以进一步重构。

最佳答案

看到_.keyBy()接受一个集合(数组或对象),您可以跳过_.values()调用:

const users = {"1":{"name":"John","email":"john@test.com","id":1,"place":"NY"},"2":{"name":"Alex","email":"alex@test.com","id":2,"place":"FL"},"3":{"name":"Tony","email":"tony@test.com","id":3,"place":"TX"}};

const result = _.keyBy(users, 'email');

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

关于javascript - Lodash:用值对象内部属性交换键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51210815/

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