Functional js, filter an object by keys

functional-programming js react

Everyone is hot for functional programming in the js world. With the explosion of React, Cycle.js, RxJs and friends, it seems convenient to abandon imperative programming in favour of functional (declarative) programming, at least when dealing with these new technologies.

If you need a brief introduction to functional programming in js, and need some info on how it differs from imperative programming, I recommend you read this article: https://www.smashingmagazine.com/2014/07/dont-be-scared-of-functional-programming/

So let's see how to solve a common problem without loops and if/else statements: how to copy an object filtering some keys. This is really an easy job for arrays, since you can use the filter function, but when dealing with objects you can't. Nevertheless we can solve the problem using another array function, which is foundamental for functional programming: reduce.

Imagine we have an object with keys a, b, c, d and we want to create a clone object with only the keys a and c, here comes the solution:

let orObj = {
  a: 'meow',
  b: 5,
  c: 7,
  d: 'lol'
let clonedFilteredObj = ['a', 'c'].reduce(
  (o, key) => {
    o[key] = orObj[key];
    return o;

Subscribe to abidibo.net!

If you want to stay up to date with new contents published on this blog, then just enter your email address, and you will receive blog updates! You can set you preferences and decide to receive emails only when articles are posted regarding a precise topic.

I promise, you'll never receive spam or advertising of any kind from this subscription, just content updates.

Subscribe to this blog

Comments are welcome!

blog comments powered by Disqus

Your Smartwatch Loves Tasker!

Your Smartwatch Loves Tasker!

Now available for purchase!