gpt4 book ai didi

javascript - Lodash uniqBy更新最新值

转载 作者:行者123 更新时间:2023-12-02 19:11:58 25 4
gpt4 key购买 nike

我有一个像下面这样的对象数组

[
{
"id": 27,
"unread_message_count": 0
},
{
"id": 27,
"unread_message_count": 7
}
]

我使用 lodash uniqBy 删除重复项,如下所示

_.uniqBy(data, 'id')

像下面这样删除重复值并返回结果

{id: 27, "unread_message_count": 0}

因为与第一个对象相比,第二个对象在 unread_message_count 中有一些更新的值。我想在 uniq 期间也更新 unread_message_count ,如下所示

let a = [{id: 27, unread_message_count: 0},{id: 27, unread_message_count: 7}];

_.uniqBy(a, 'id')

Output:

{id: 27, unread_message_count: 7}

最佳答案

您可以反转数组,找到唯一值,然后反转回去:

const arr = [{id: 27, unread_message_count: 0},{id: 27, unread_message_count: 7}];

const result = _.reverse(_.uniqBy(_.reverse([...arr]), 'id'));

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>

另一种选择是将数组缩减为 Map,并始终从相同的项目中获取最新的对象:

const arr = [{id: 27, unread_message_count: 0},{id: 27, unread_message_count: 7}];

const result = Array.from(
arr.reduce(
(r, o) => r.set(o.id, o),
new Map()
).values());

console.log(result);

关于javascript - Lodash uniqBy更新最新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64171841/

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