PickProps
The easiest way to filter properties from an object
// How to filter "a" and "c" from obj
var obj = { a:1, b:2, c:3, d:4 }
pickProps( ({ a, c }) => obj );
//=> { a:1, c:3 }
How to Use:
It works just like destructuring. Just call pickProps() passing a function that:
- has a destructred object as an argument, and
- returns the object you are pickering from
Example:
import pickProps from 'PickProps'
// How to pick only name and job from a person object
var person = {
name: 'John',
age: 33,
job: 'Designer',
city: 'New York'
}
pickProps( ({ name, job }) => person );
//=> { name: 'John', job: 'Designer' }
You can also get the data as an array. Just set 'array' as the second parameter
Example:
// How to pick the data as an array
pickProps( ({ name, job }) => person, 'array' );
//=> ['John', 'Designer']
Other Examples
Fetching Data
without PickProps:
function fetchData(){
const response = api.get('http://localhost:8080/person/10');
// destructuring specific properties from and object
const { name, age, height, job, city } = response;
// but now you need to pass an object with the same properties (redundancy 😩)
setData({
name,
age,
height,
job,
city
})
}
using PickProps:
function fetchData(){
const response = api.get('http://localhost:8080/person/10');
// getting a filtered object with the specific properties
const personData = pickProps( ({ name, age, height, job, city }) => response )
// now just use it 🤗
setData(personData)
}
How to Install
- Install it using npm or yarn
npm install --save pickprops
yarn add pickprops
- Import it
import pickProps from 'pickprops'
- Use it
😄