Merge property from an array of objects into another based on property value lodash

前端 未结 4 1234
逝去的感伤
逝去的感伤 2020-12-10 09:54

I have 2 arrays of objects, they each have an id in common. I need a property from objects of array 2 added to objects array 1, if they have matching id<

4条回答
  •  隐瞒了意图╮
    2020-12-10 10:14

    A solution in plain Javascript

    This is a more generic solution for merging two arrays which have different properties to union in one object with a common key and some properties to add.

    var array1 = [{ id: 1, name: 'tom', age: 24 }, { id: 2, name: 'tim', age: 25 }, { id: 3, name: 'jack', age: 24 }, ],
        array2 = [{ id: 1, gender: 'male', eyeColour: 'blue', weight: 150 }, { id: 2, gender: 'male', eyeColour: 'green', weight: 175 }, { id: 3, gender: 'male', eyeColour: 'hazel', weight: 200 }, ];
    
    function merge(a, b, id, keys) {
        var array = [], object = {};
    
        function m(c) {
            if (!object[c[id]]) {
                object[c[id]] = {};
                object[c[id]][id] = c[id];
                array.push(object[c[id]]);
            }
            keys.forEach(function (k) {
                if (k in c) {
                    object[c[id]][k] = c[k];
                }
            });
        }
        a.forEach(m);
        b.forEach(m);
        return array;
    }
    
    document.write('
    ' + JSON.stringify(merge(array1, array2, 'id', ['name', 'age', 'eyeColour']), 0, 4) + '
    ');

提交回复
热议问题