JS - deep map function

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

    Here is a clean ES6 version:

    function mapObject(obj, fn) {
      return Object.keys(obj).reduce(
        (res, key) => {
          res[key] = fn(obj[key]);
          return res;
        },
        {}
      )
    }
    
    function deepMap(obj, fn) {
      const deepMapper = val => typeof val === 'object' ? deepMap(val, fn) : fn(val);
      if (Array.isArray(obj)) {
        return obj.map(deepMapper);
      }
      if (typeof obj === 'object') {
        return mapObject(obj, deepMapper);
      }
      return obj;
    }
    

提交回复
热议问题