JS - deep map function

后端 未结 8 549
挽巷
挽巷 2020-12-06 04:48

Underscore.js has a very useful map function.

_.map([1, 2, 3], function(num){ return num * 3; });
=> [3, 6, 9]
_.map({one: 1, two: 2, three: 3         


        
8条回答
  •  难免孤独
    2020-12-06 05:19

    Here's my version - slightly lengthy so I expect it can be shortened, but works with arrays and objects and no external dependencies:

    function deepMap(obj, f, ctx) {
        if (Array.isArray(obj)) {
            return obj.map(function(val, key) {
                return (typeof val === 'object') ? deepMap(val, f, ctx) : f.call(ctx, val, key);
            });
        } else if (typeof obj === 'object') {
            var res = {};
            for (var key in obj) {
                var val = obj[key];
                if (typeof val === 'object') {
                    res[key] = deepMap(val, f, ctx);
                } else {
                    res[key] = f.call(ctx, val, key);
                }
            }
            return res;
        } else {
            return obj;
        }
    }
    

    demo at http://jsfiddle.net/alnitak/0u96o2np/

    EDIT slightly shortened now by using ES5-standard Array.prototype.map for the array case

提交回复
热议问题