Filtering keys

You can use map() to transform a list of maps into one that only has the keys that you need. To do this, you can implement a couple of utility functions that compose iteratees for you, as follows:

const pick = (...props) => map => map
.filter((v, k) => props.includes(k));
const omit = (...props) => map => map
.filterNot((v, k) => props.includes(k));

The pick() function returns an iteratee that will return a map that only includes the keys that are passed to pick(). The omit() function is the inverse of pick()—it will include everything except the keys passed to omit(). Let's see how they work here:

const myList = List.of(
Map.of('first', 'joe', 'last', 'brown', 'age', 45),
Map.of('first', 'john', 'last', 'smith', 'age', 32),
Map.of('first', 'mary', 'last', 'wise', 'age', 56)
);
const myPickedList = myList.map(pick('first', 'last'));
const myOmittedList = myList.map(omit('first', 'last'));

console.log('myList', myList.toJS());
// -> myList [ { first: 'joe', last: 'brown', age: 45 },
// -> { first: 'john', last: 'smith', age: 32 },
// -> { first: 'mary', last: 'wise', age: 56 } ]

console.log('myPickedList', myPickedList.toJS());
// -> myPickedList [ { first: 'joe', last: 'brown' },
// -> { first: 'john', last: 'smith' },
// -> { first: 'mary', last: 'wise' } ]

console.log('myOmittedList', myOmittedList.toJS());
// -> myOmittedList [ { age: 45 },
// -> { age: 32 },
// -> { age: 56 } ]

You can see that myPickedList only includes the keys that were passed to pick() and myOmittedList. It doesn't include any keys that were passed to omit().

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.134.29