JS - deep map function

后端 未结 8 523
挽巷
挽巷 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's the function I just worked out for myself. I'm sure there's a better way to do this.

    // function
    deepMap: function(data, map, key) {
      if (_.isArray(data)) {
        for (var i = 0; i < data.length; ++i) {
          data[i] = this.deepMap(data[i], map, void 0);
        }
      } else if (_.isObject(data)) {
        for (datum in data) {
          if (data.hasOwnProperty(datum)) {
            data[datum] = this.deepMap(data[datum], map, datum);
          }
        }
      } else {
        data = map(data, ((key) ? key : void 0));
      }
      return data;
    },
    
    // implementation
    data = slf.deepMap(data, function(val, key){
      return (val == 'undefined' || val == 'null' || val == undefined) ? void 0 : val;
    });
    

    I cheated on using underscore.

提交回复
热议问题