通过ID从数组Ramda中删除对象

时间:2019-08-08 09:54:57

标签: javascript functional-programming ramda.js

我想使用Ramda通过ID从数组中删除对象。例如:

const arr = [
  {id: '1', name: 'Armin'},
  {id: '2', name: 'Eren'}, <- delete this object
  {id: '3', name: 'Mikasa'}
];

4 个答案:

答案 0 :(得分:4)

您可以同时使用filterreject

R.reject(o => o.id === '2', arr);

R.filter(o => o.id !== '2', arr);

答案 1 :(得分:3)

您可以使用具有组合功能的filter功能来使用propEq & not

const result = filter(
  compose(
   not,
   propEq('id', 2)
  ),
  array,
)
console.log(result)

答案 2 :(得分:3)

您可以使用reject

  

reject()是filter()的补充。它不包括   谓词返回true的可过滤器。

let res = R.reject(R.propEq('id', '2'))(arr);

答案 3 :(得分:1)

// 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>