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

Categories

0 votes
340 views
in Technique[技术] by (71.8m points)

javascript - Merge objects in array based on property

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

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

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...