Functional js, filter an object by keys
You can also be interested in:
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; }, {} );
Your Smartwatch Loves Tasker!
Your Smartwatch Loves Tasker!
Featured
Archive
- 2021
- 2020
- 2019
- 2018
- 2017
- Nov
- Oct
- Aug
- Jun
- Mar
- Feb
- 2016
- Oct
- Jun
- May
- Apr
- Mar
- Feb
- Jan
- 2015
- Nov
- Oct
- Aug
- Apr
- Mar
- Feb
- Jan
- 2014
- Sep
- Jul
- May
- Apr
- Mar
- Feb
- Jan
- 2013
- Nov
- Oct
- Sep
- Aug
- Jul
- Jun
- May
- Apr
- Mar
- Feb
- Jan
- 2012
- Dec
- Nov
- Oct
- Aug
- Jul
- Jun
- May
- Apr
- Jan
- 2011
- Dec
- Nov
- Oct
- Sep
- Aug
- Jul
- Jun
- May