Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

var array = [ 
    {name: "One",
     myList: [Object1, Object2]
    },
    {name: "Two",
     myList: [Object3, Object4]
     },
     {name: "One",
     myList: [Object5, Object6]
     }
]

How do i merge the two 'One' objects so i get something like

var array = [ 
    {name: "One",
     myList: [Object1, Object2, Object5, Object6]
    },
    {name: "Two",
     myList: [Object3, Object4]
     }
]

looking to do this in vanilla javascript

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
342 views
Welcome To Ask or Share your Answers For Others

1 Answer

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;
}, []);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...