我有一个对象,{thing1: {}, thing2: {}},有一种方法可以覆盖像{thing1: {}, thing3not2: {}}这样的道具名称
发布于 2018-08-21 08:39:02
不确定是否有一种更快/更简单的方法,但是可以将assoc添加新键和dissoc组合以删除旧键:
const { curry, assoc, dissoc } = R;
const renameProp = curry(
(oldName, newName, obj) =>
dissoc(oldName, assoc(newName, obj[oldName], obj))
);
const myTransformation = renameProp("thing2", "thing3not2");
const myResult = myTransformation( {thing1: {}, thing2: {} } );
console.log(JSON.stringify(myResult, null, 4));<script src="https://cdn.jsdelivr.net/npm/ramda@0.25.0/dist/ramda.min.js"></script>
发布于 2018-08-21 13:31:09
Ramda“食谱”包含一个renameKeys函数https://github.com/ramda/ramda/wiki/Cookbook#rename-keys-of-an-object
下面是从那里复制的:
/**
* Creates a new object with the own properties of the provided object, but the
* keys renamed according to the keysMap object as `{oldKey: newKey}`.
* When some key is not found in the keysMap, then it's passed as-is.
*
* Keep in mind that in the case of keys conflict is behaviour undefined and
* the result may vary between various JS engines!
*
* @sig {a: b} -> {a: *} -> {b: *}
*/
const renameKeys = R.curry((keysMap, obj) =>
R.reduce((acc, key) => R.assoc(keysMap[key] || key, obj[key], acc), {}, R.keys(obj))
);并称之为
renameKeys({thing2: 'thing3not2'}, {thing1: {}, thing2: {}})
=> {"thing1": {}, "thing3not2": {}}https://stackoverflow.com/questions/51940748
复制相似问题