Easily reshape objects with TS support
Installation
npm install shapify# or yarn install shapify
Usage
Basic usage
Given an array of users:
const users = fullname: 'Eduardo San Martin morote' id: 1 more: 'properties' that: 'exist' but: "you don't always need" // more users
You can transform objects
const reshapedUser = /** * only text and value are present * { text: 'Eduardo San Martin Morote', value: 1 } */
Functional approach
This can be used to transform whole arrays of objects:
// create a function with the first parameter fixedconst userShaper = // equivalent toconst sameUserShaper = shapify // generate the new arrayconst userChoices = users
⚠️: (#3) this breaks typings (mark them as unknown
), if you know how to make it work, please file a PR
Customizing the new value
If you want to customize the value instead of just using the original one, you can provide a function:
const reshapedUser = /** * only text and value are present * { text: 'Eduardo San Martin Morote', value: 'id: 1' } */
Keeping original keys/values
If you need to keep original keys, you can provide a key with the same value:
But a more appropriate syntax is an array of keys (strings, numbers or symbols):
This is similar to lodash.pick(users[0], ['id', 'fullname'])
. However, because shapify is type safe, it cannot support paths as strings as lodash.pick
does. Instead you need to use a function.
If you need to keep all of the original keys, there is a helper that you can use:
// this will generate a user object with all of the original properties as well// as text with fullname's value