Merging objects (associative arrays)

前端 未结 16 1239
野的像风
野的像风 2020-12-04 08:20

What’s the best/standard way of merging two associative arrays in JavaScript? Does everyone just do it by rolling their own for loop?

16条回答
  •  死守一世寂寞
    2020-12-04 08:44

    Recursive solution (extends also arrays of objects) + null checked

    var addProps = function (original, props) {
        if(!props) {
            return original;
        }
        if (Array.isArray(original)) {
            original.map(function (e) {
                return addProps(e, props)
            });
            return original;
        }
        if (!original) {
            original = {};
        }
        for (var property in props) {
            if (props.hasOwnProperty(property)) {
                original[property] = props[property];
            }
        }
        return original;
    };
    

    Tests

    console.log(addProps([{a: 2}, {z: 'ciao'}], {timestamp: 13}));
    console.log(addProps({single: true}, {timestamp: 13}));
    console.log(addProps({}, {timestamp: 13}));
    console.log(addProps(null, {timestamp: 13}));
    
    [ { a: 2, timestamp: 13 }, { z: 'ciao', timestamp: 13 } ]
    { single: true, timestamp: 13 }
    { timestamp: 13 }
    { timestamp: 13 }
    

提交回复
热议问题