javascript - 使用 ramda 修改对象数组中的属性

标签 javascript arrays ramda.js

我正在尝试使用 ramda 从对象数组中删除一些属性。我有一系列属性需要删除,例如:

const colToHide = ['name', 'age']; 
// those properties are selected by the user 

我想从一组对象中删除属性 'name''age' (或任何用户选择的属性)。对象数组是这样的:

const person = [
  {name:'sam', age:'24', address:'xyz avenue', employed:true},
  {name:'john', age:'25', address:'xyz avenue', employed:true}
];

更新该对象数组的正确方法是什么?

最佳答案

您可以使用.omit()方法与 .map() 结合使用。像这样的事情:

const person = [
  {name:'sam', age:'24', address:'xyz avenue', employed:true},
  {name:'john', age:'25', address:'xyz avenue', employed:true}
]

const omitKeys = (keys, arr) => R.map(R.omit(keys), arr);

console.log(omitKeys(["name", "age"], person));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>

更重要的是,您可以使用.compose()正如@ScottSauyet 在评论中建议的那样:

const omitKeys = R.compose(R.map, R.omit);

然后将其用作:

omitKeys(["name", "age"])(person);

const person = [
  {name:'sam', age:'24', address:'xyz avenue', employed:true},
  {name:'john', age:'25', address:'xyz avenue', employed:true}
]

const omitKeys = R.compose(R.map, R.omit);

console.log(omitKeys(["name", "age"])(person));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>

关于javascript - 使用 ramda 修改对象数组中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56588271/

相关文章:

javascript - ReadStream和WriteStream到nodejs中的同一个文件

javascript - $event.stopPropagation() 运行但父事件仍然执行

c++ - 启动具有特定变量值的派生类

arrays - VBA - MsgBox 二维数组(矩阵)

javascript - 如何使用 Babel 在 Rollup 中设置 Ramda(以使用 ES6 导入)

javascript - Rx js过滤器方法不返回过滤器数组

javascript - 使用字符串替换将变量传递到正则表达式

c - 快速替换数组中元素的方法 - C

javascript - ramda 数组清理数据以生成唯一的数组

javascript - 如何重构这个命令式 JS 使其具有功能性?