Merging objects (associative arrays)

前端 未结 16 1219
野的像风
野的像风 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 09:09

    Rolling Your Own Extend/Mixin Function

    function extend(objects) {
        var args
            , first = Array.prototype.slice.call(arguments, 0, 1)[0]
            , second;
    
        if (arguments.length > 1) {
            second = Array.prototype.splice.call(arguments, 1, 1)[0];
            for (var key in second) {
                first[key] = second[key];
            }
            args = Array.prototype.slice.call(arguments, 0);
            return extend.apply(this, args);
        }
    
        return first;
    }
    

    ...

    var briansDirections = {
        step1: 'Remove pastry from wrapper.',
        step2: 'Place pastry toaster.',
        step3: 'Remove pastry from toaster and enjoy.',
    };
    extend(briansDirections, { step1: 'Toast Poptarts' }, { step2: 'Go ahead, toast \'em' }, { step3: 'Hey, are you sill reading this???' });
    

    ...

    This simply extends a splat of objects, recursively. Also, note that this recursive function is TCO (Tail-Call Optimized) as its return is the last call to itself.

    Additionally, you may want targeted properties. In this case, you may want to condense objects based upon id, quantity, or another property. This approach could have a small book written about it and requires object-juxtaposition and can get very complex. I've written a small library for this which is available upon request.

    Hope this helps!

提交回复
热议问题