user429035
user429035

Reputation: 471

Using ramda to modify a property in array of Objects

I am trying to remove some properties from an array of objects using ramda. I have an array of properties to remove like:

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

And I want to remove the properties 'name' and 'age' (or any user selected property) from one array of objects. The array of objects is something like this:

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

What would be right way to update that array of object?

Upvotes: 2

Views: 809

Answers (2)

Shidersz
Shidersz

Reputation: 17190

You can use the .omit() method in conjunction with a .map(). Something like this:

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>

Even more, you can use .compose() as @ScottSauyet proposed on the comments to do:

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

And then use it as:

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>

Upvotes: 2

Hitmands
Hitmands

Reputation: 14199

or in a point free style using 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>

Upvotes: 2

Related Questions