JS - deep map function

后端 未结 8 522
挽巷
挽巷 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:27

    Based on @megawac response, I made some improvements.

    function mapExploreDeep(object, iterateeReplace, iterateeExplore = () => true) {
        return _.transform(object, (acc, value, key) => {
            const replaced = iterateeReplace(value, key, object);
            const explore = iterateeExplore(value, key, object);
            if (explore !== false && replaced !== null && typeof replaced === 'object') {
                acc[key] = mapExploreDeep(replaced, iterateeReplace, iterateeExplore);
            } else {
                acc[key] = replaced;
            }
            return acc;
        });
    }
    
    _.mixin({
        mapExploreDeep: mapExploreDeep;
    });
    

    This version allows you to replace even objects & array themselves, and specify if you want to explore each objects/arrays encountered using the iterateeExplore parameter.

    See this fiddle for a demo

提交回复
热议问题