Lodash _.renameKeys() 方法
Lodash _.renameKeys() 方法接受一个对象和一个映射对象,并返回一个新对象,其中给定对象的键已重命名为 keyMap 中的相应值。
句法:
_.renameKeys(obj, mapObj);
参数:此方法接受上面提到的两个参数,如下所述:
- obj:给定对象创建一个新对象。
- mapObj:给定地图对象创建一个新对象。
返回值:该方法返回一个生成的对象。
注意:这在普通 JavaScript 中不起作用,因为它需要安装 lodash.js contrib 库。 Lodash.js contrib 库可以使用以下命令安装:
npm install lodash-contrib
示例 1:
// Defining underscore lodash variable
var _ = require('lodash-contrib');
// Declare and object and rename its key
var obj = _.renameKeys( { 1 : "Geeks",
2 : "Computer_Science_Portal" },
{ 1 : "g", 2 : "c" });
console.log("Generated Object: ", obj);
输出:
Generated Object: Object {c: "Computer_Science_Portal", g: "Geeks"}
示例 2:
// Defining underscore lodash variable
var _ = require('lodash-contrib');
// Declare and object and rename its key
var obj = _.renameKeys(
{ 1 : "Geeks", 2 : "Computer_Science_Portal",
3 : "Geeks" }, { 1 : "g", 2 : "c", 3 : "g" });
console.log("Generated Object: ", obj);
输出:
Generated Object: Object {c: "Computer_Science_Portal", g: "Geeks"}
示例 3:
// Defining underscore lodash variable
var _ = require('lodash-contrib');
// Declare and object and rename its key
var obj = _.renameKeys( [ "Computer_Science_Portal", "Geeks" ],
{ 0 : "a", 1 : "b", 3 : "g" });
console.log("Generated Object: ", obj);
输出:
Generated Object: Object {c: "Computer_Science_Portal", g: "Geeks"}