Is there any way to rename js object keys using underscore.js

后端 未结 13 1808
小蘑菇
小蘑菇 2020-12-05 01:21

I need to convert a js object to another object for passing onto a server post where the names of the keys differ for example

var a = {
    name : \"Foo\",
          


        
13条回答
  •  不思量自难忘°
    2020-12-05 02:16

    You can create your new custom function :

    lodash.rename = function(obj, keys, newKeys) {
      keys.map((key, index) => {
        if(lodash.includes(lodash.keys(obj), key)) {
          obj[newKeys[index]] = lodash.clone(obj[key], true);
          delete obj[key];
        }
      });
      return obj;
    };
    

    Or else if you want to edit only one keyName:

    lodash.rename = function(obj, key, newKey) {
        if(lodash.includes(lodash.keys(obj), key)) {
          obj[newKeys[index]] = lodash.clone(obj[key], true);
          delete obj[key];
        }
      return obj;
    };
    
    

提交回复
热议问题