JavaScript merging objects by id

前端 未结 16 1899
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 09:43

What\'s the correct way to merge two arrays in Javascript?

I\'ve got two arrays (for example):

var a1 = [{ id : 1, name : \"test\"}, { id : 2, name :         


        
16条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 10:31

    You can write a simple object merging function like this

    function mergeObject(cake, icing) {
        var icedCake = {}, ingredient;
        for (ingredient in cake)
            icedCake[ingredient] = cake[ingredient];
        for (ingredient in icing)
            icedCake[ingredient] = icing[ingredient];
        return icedCake;
    }
    

    Next, you need to do use a double-loop to apply it to your data structre

    var i, j, a3 = a1.slice();
    for (i = 0; i < a2.length; ++i)                // for each item in a2
        for (j = 0; i < a3.length; ++i)            // look at items in other array
            if (a2[i]['id'] === a3[j]['id'])       // if matching id
                a3[j] = mergeObject(a3[j], a2[i]); // merge
    

    You can also use mergeObject as a simple clone, too, by passing one parameter as an empty object.

提交回复
热议问题