我正在尝试使用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}
];
更新该对象数组的正确方法是什么?
答案 0 :(得分:2)
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>