【发布时间】:2017-12-23 21:56:19
【问题描述】:
我正在尝试使用 lodash 首先计算对象数组中有多少重复项,然后删除重复项(保留计数器)。
到目前为止,我的代码似乎可以工作,但我无法弄清楚如何将两者合并(抱歉,用 lodash 新建)。
这里有一些代码:
var array = [
{id: 1, name: "test"},
{id: 2, name: "test 2"},
{id: 3, name: "test 3"},
{id: 4, name: "test 4"},
{id: 1, name: "test "},
{id: 2, name: "test 2"},
]
// This finds the duplicates and removes them
result = _.uniqBy(array, 'id')
// this counts how many duplicates are in the array
count = _(result)
.groupBy('id')
.map((items, name) => ({ name, count: items.length }))
.value();
我想清点,然后去掉但保持清点,这样最终的结果就基本告诉我订单中有多少产品,但保持不变,数量从1变为2。
我确实尝试过,但它不起作用:
result = _(result)
.groupBy('id')
.map((items, name) => ({ name, count: items.length }))
.uniqBy(result, 'name')
.value()
这会给我这样的东西:
result = [
{id: 1, name: "test", qty: 2},
{id: 2, name: "test 2", qty: 2},
{id: 3, name: "test 3", qty: 1},
{id: 4, name: "test 4", qty: 1}
]
有什么帮助吗?
谢谢
【问题讨论】:
-
你能给我们一个预期结果的例子吗?
-
@syntagma 请检查已编辑的问题