有没有一种使用underscore.js重命名js对象键的方法?

66

我需要将一个JavaScript对象转换为另一个对象,以便在向服务器发送POST请求时使用。但是需要注意的是,目标对象的键名与原对象不同。

var a = {
    name : "Foo",
    amount: 55,
    reported : false,
    ...
    <snip/>
    ...
    date : "10/01/2001"
    } 

需要转换为

a = {
  id : "Foo",
  total : 55,
  updated: false,
  ...
  <snip/>
  ... 
  issued : "10/01/2001"
  }

我有一个lookup对象可用于映射所有键

var serverKeyMap = {
    name : "id",
    amount : "total",
    reported : "updated",
     ...
    date : "issue"
    }
有没有在underscore.js或jQuery中可用的函数,我可以使用来实现这个功能?
谢谢。

8
不是下划线(underscore),而是 Lodash 提供了 _.mapKeys 方法来修改对象的键。 - CookieEater
16个回答

1
我查阅了lodash文档,发现了mapKeys函数。 https://lodash.com/docs/4.17.15#mapKeys
_.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
  return key + value;
});
// => { 'a1': 1, 'b2': 2 }

这个函数可以完美地重命名键,并返回一个包含修改后的理想对象的对象。

1

正如用户2387823所说,以上使用省略是一个很好的选择。例如,你可以写出这样的内容

function updateObjKey(obj, currentKey, newKey) {
    var keyValue = obj[currentKey];
    obj = _.omit(obj, [currentKey]);
    obj[newKey] = keyValue;
    return obj;
  }

1

this ES2015/2017 version ‍♂️

function objectMap(source,keyMap) {
    return Object.entries(keyMap).reduce((o,[key , newKey]) => {
            o[newKey]=source[key]
            return o;},{})
}

const obj = {
    name : "Foo",
    amount: 55,
    reported : false,
    date : "10/01/2001"
    }
    
const  serverKeyMap = {
    name : "id",
    amount : "total",
    reported : "updated",
    date : "issue"
    }
    
const result = objectMap(obj,serverKeyMap);

console.log(' =>' , result);

[Object.entries][1] is es2017 feture will return object key and value as array

[["name", "id"],["amount", "total"],...]

0

使用lodash

var obj = _.renameKeys( { 1 : "Geeks",  
            2 : "Computer_Science_Portal" }, 
            { 1 : "g", 2 : "c" }); 

所以在你的情况下,你想将 serverKeyMap 应用到对象 a 上:

var obj = _.renameKeys(a, serverKeyMap);

来自https://www.geeksforgeeks.org/lodash-_-renamekeys-method/


1
为了明确起见:此函数并非内置于 Lodash,而是由 lodash-contrib 包添加的扩展。同样地,在 Underscore 中有一个 renameKeys 函数在 Underscore-contrib 中(可能是 lodash-contrib 的一个分支):http://documentcloud.github.io/underscore-contrib/#renamekeys。 - Julian

0

你可以创建自己的新函数:

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;
};

或者如果您只想编辑一个键名:

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;
};


0

使用下划线omit和展开运算符。

a = _.omit({
  ...a,
  id: a.name,
  total: a.amount,
  updated: a.reported,
}, ['name', 'amount', 'reported']);

在扩展运算符下面的键分配会加载新键并省略旧键。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接