Merge objects in array based on property

前端 未结 3 1804
悲哀的现实
悲哀的现实 2020-12-21 08:03

I have an array like so which i am trying to merge so any object that has the name property the same will after the merge contain a list of merged objects

va         


        
3条回答
  •  南方客
    南方客 (楼主)
    2020-12-21 08:32

    Using reduce:

    var merged = array.reduce(function(list, obj) {
        var found = false;
        for (var i = 0; i < list.length; i++) {
            if (list[i].name == obj.name) {
                list[i].myList = list[i].myList.concat(obj.myList);
                found = true;
                break;
            }
        }
    
        if (!found) {
            list.push(obj);
        }
    
        return list;
    }, []);
    

提交回复
热议问题