从数组 Ramda 中按 id 删除对象
Delete object by id from array Ramda
我想使用 Ramda 按 id 从数组中删除对象。例如:
const arr = [
{id: '1', name: 'Armin'},
{id: '2', name: 'Eren'}, <- delete this object
{id: '3', name: 'Mikasa'}
];
您可以使用 filter
函数,使用组合函数 propEq & not
const result = filter(
compose(
not,
propEq('id', 2)
),
array,
)
console.log(result)
您可以使用 reject
.
The reject() is a complement to the filter(). It excludes elements of
a filterable for which the predicate returns true.
let res = R.reject(R.propEq('id', '2'))(arr);
您可以同时使用 filter
或 reject
:
R.reject(o => o.id === '2', arr);
R.filter(o => o.id !== '2', arr);
// you could create a generic rejectWhere function
const rejectWhere = (arg, data) => R.reject(R.whereEq(arg), data);
const arr = [
{id: '1', name: 'Armin'},
{id: '2', name: 'Eren'}, // <- delete this object
{id: '3', name: 'Mikasa'}
];
console.log(
'result',
rejectWhere({ id: '2' }, arr),
);
// but also
// rejectWhere({ name: 'Eren' }, arr),
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js" integrity="sha256-xB25ljGZ7K2VXnq087unEnoVhvTosWWtqXB4tAtZmHU=" crossorigin="anonymous"></script>
我想使用 Ramda 按 id 从数组中删除对象。例如:
const arr = [
{id: '1', name: 'Armin'},
{id: '2', name: 'Eren'}, <- delete this object
{id: '3', name: 'Mikasa'}
];
您可以使用 filter
函数,使用组合函数 propEq & not
const result = filter(
compose(
not,
propEq('id', 2)
),
array,
)
console.log(result)
您可以使用 reject
.
The reject() is a complement to the filter(). It excludes elements of a filterable for which the predicate returns true.
let res = R.reject(R.propEq('id', '2'))(arr);
您可以同时使用 filter
或 reject
:
R.reject(o => o.id === '2', arr);
R.filter(o => o.id !== '2', arr);
// you could create a generic rejectWhere function
const rejectWhere = (arg, data) => R.reject(R.whereEq(arg), data);
const arr = [
{id: '1', name: 'Armin'},
{id: '2', name: 'Eren'}, // <- delete this object
{id: '3', name: 'Mikasa'}
];
console.log(
'result',
rejectWhere({ id: '2' }, arr),
);
// but also
// rejectWhere({ name: 'Eren' }, arr),
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js" integrity="sha256-xB25ljGZ7K2VXnq087unEnoVhvTosWWtqXB4tAtZmHU=" crossorigin="anonymous"></script>