Javascript 使用lodash合并连接值的对象

Javascript 使用lodash合并连接值的对象,javascript,lodash,Javascript,Lodash,我试图操纵这个对象的示例数组 [ { name: 'John Wilson', id: 123, classes: ['java', 'c++']}, { name: 'John Wilson', id: 123, classes: 'uml'}, { name: 'Jane Smith', id: 321, classes: 'c++'} ] 我需要做的是合并具有相同“id”的对象,连接“类”并保留一个“名称” 结果应该是: [ {

我试图操纵这个对象的示例数组

[ { name: 'John Wilson',
    id: 123,
    classes: ['java', 'c++']},
  { name: 'John Wilson',
    id: 123,
    classes: 'uml'},
   { name: 'Jane Smith',
    id: 321,
    classes: 'c++'} ]
我需要做的是合并具有相同“id”的对象,连接“类”并保留一个“名称”

结果应该是:

[ { name: 'John Wilson',
    id: 123,
    classes: ['java', 'c++', 'uml']},
   { name: 'Jane Smith',
    id: 321,
    classes: 'c++'} ]
我尝试使用.merge,但它没有连接来自“类”的值,它只是保留来自最后一个相等对象的值


使用lodash最简单的方法是什么?

不确定使用lodash。。。下面是一种使用普通JS的方法:

var combined = arr.reduce(function(a, item, idx) {
    var found = false;
    for (var i = 0; i < a.length; i++) {
        if (a[i].id == item.id) {
            a[i].classes = a[i].classes.concat(item.classes);
            found = true;
            break;
        }
    }

    if (!found) {
        a.push(item);
    }

    return a;
}, []);
var combined=arr.reduce(功能(a,项目,idx){
var=false;
对于(变量i=0;i

小提琴:

您正在寻找的函数是,带有一个特殊的扭曲,我将在一分钟内解释

uniqWith
非常类似于它生成一个唯一的数组,但它允许您传递自己的自定义比较器函数,该函数将被调用以确定什么是“相等”

理智的程序员会明白,这个比较器应该没有副作用。这段代码的工作方式是打破这一规则,并使用一个在幕后具有额外魔力的比较函数。然而,这会产生非常简洁的代码,无论数组中有多少这样的对象,这些代码都能正常工作,所以我觉得这样做是有道理的

我将comparator函数命名为
compareAndMerge
,以避免隐藏其不纯性质。它将合并两个
数组并更新两个对象上的相关属性,但前提是它们的
id
值相同

功能合并(人员){
return uqwith(人员、比较和合并)
}
函数compareAndMerge(第一,第二){
if(first.id==second.id){
first.classes=second.classes=[].concat(first.classes,second.classes)
返回真值
}
返回错误
}
var people=[{
姓名:“约翰·威尔逊”,
id:123,
类:['java','c++']
}, {
姓名:“约翰·威尔逊”,
id:123,
类:“uml”
}, {
姓名:“简·史密斯”,
身份证号码:321,
类:“c++”
}]
console.log(合并(人员))
用于设置合并自定义项

_.reduce(data, function(result, item) {
    item = _.mergeWith(
        item,
        _.find(result, {id: item.id}),
        function(val, addVal) {
            return _.isArray(val) ? _.concat(val, addVal) : val;
        });
    result = _.reject(result, {id: item.id})
    return _.concat(result, item);
}, []);

下面的算法不是最好的,但至少我知道它的作用:-)

console.log(清除(数据));
函数清理(数据){
变量i,x,y;
var clean=[];
var m=净长度;
var n=数据长度;
data.sort((x,y)=>x.id-y.id);
对于(i=0;i

风险值数据=[{
id:123,
姓名:“约翰·威尔逊”,
类:['java','c++']
}, {
id:123,
姓名:“约翰·威尔逊”,
类:['uml','java']
}, {
身份证号码:321,
姓名:“简·史密斯”,
类:['c++']
}];

使用ES6,您可以使用保存唯一值、填充唯一值以及将其转换回数组的:

const arr=[{“name”:“John Wilson”,“id”:123,“classes”:[“java”,“c++”]},{“name”:“John Wilson”,“id”:123,“classes”:“uml”},{“name”:“Jane Smith”,“id”:321,“classes”:“c++”};
const result=[…arr.reduce((散列,{id,name,classes})=>{
const current=hash.get(id)|{id,name,class:[]};
类&(current.classes=current.classes.concat(classes));
返回hash.set(id,current);
},新映射)。值();

控制台日志(结果)这真的很聪明,也很有创意+感谢您对ES6的全面了解。谢谢!我实际上忘记了括号。代码是干净的,工作得很好。很高兴能提供帮助!一路上我也学到了不少关于洛达斯的知识。