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

时间:2019-06-13 20:38:48

标签: 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}
];

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

2 个答案:

答案 0 :(得分:2)

您可以将.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>

答案 1 :(得分:2)

或使用R.useWith以无点样式:

const omit = R.useWith(R.map, [
  R.omit, 
  R.identity,
]);

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

console.log(
  'result',
  omit(["name", "age"], persons),
);
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>