How to deeply map object keys with JavaScript (lodash)?

前端 未结 5 651
刺人心
刺人心 2021-02-02 12:48

https://lodash.com/docs#mapKeys

Is it possible to map an Object\'s keys deeply using Lodash? If not, is there another library providing this functionality (if grouped wi

5条回答
  •  温柔的废话
    2021-02-02 13:18

    EDIT: This will map the objects values, not its keys. I misunderstood the question.


    function deepMap (obj, cb) {
        var out = {};
    
        Object.keys(obj).forEach(function (k) {
          var val;
    
          if (obj[k] !== null && typeof obj[k] === 'object') {
            val = deepMap(obj[k], cb);
          } else {
            val = cb(obj[k], k);
          }
    
          out[k] = val;
        });
    
      return out;
    }
    

    And use it as

    var lol = deepMap(test, function (v, k) {
        return v + '_hi';
    });
    

    It will recursively iterate over an objects own enumerable properties and call a CB passing it the current value and key. The values returned will replace the existing value for the new object. It doesn't mutate the original object.

    See fiddle: https://jsfiddle.net/1veppve1/

提交回复
热议问题