使用Lotash合并单个数组中的重复对象

人气:952 发布:2022-10-16 标签: javascript json arrays lodash underscore.js

问题描述

我正在尝试合并收到的json数组中的重复对象。

数组如下所示:

{
  modules: [{
    "name": "Weazel",
    "otherprop": ["a", "b"]
  }, {
    "name": "weazel",
    "otherprop": ["c", "b"]
  }]
}

由于某些原因,我想不出如何合并重复项。

我尝试过先将所有名称映射为小写,然后使用Unique,但这样会删除其他属性的值。

let result = _.map(json.modules, mod => { mod.name = mod.name.tolower(); return mod; });
result = _.unique(result, 'name');

有人知道如何使用Lotash来撞击我的问题吗?

推荐答案

var result = _.uniq(json.modules, function(item, key, a) { 
        return item.a;
    });

//Result : [{"name":"Weazel","otherprop":["a","b"]}]

768