Converts an array to object, with custom key and value.
npm i @dantehemerson/arr2obj
or with yarn:
yarn add @dantehemerson/arr2obj
You can import as follows:
const { arr2obj } = require('@dantehemerson/arr2obj')The function is:
array: The array to transform.
options: The options sould be a object with two optional keys: key and value, functions that receive the item as argument and return a value.
-
key: Function that must return the value that will be taken as the key. -
value: Function that must return the value that will be taken as value.
for example:
{
key: item => `pre-${item}`,
value: item => item
}If you use Typescript, the interface of options is:
interface Options {
key?: (item: any) => object | number | string | boolean
value?: (item: any) => object | number | string | boolean
}Object tranformed.
const result = arr2obj(['a', 'b', 'c'])
// result:
// { a: 'a', b: 'b', c: 'c' }const arr = [
{
id: 1
},
{
id: 2
},
{
id: 3
}
]
const result = arr2obj(arr, {
key: item => `pre-${item}-post`,
value: item => Math.pow(item, 2)
})
/**
result:
{
1: {
id: 1
},
2: {
id: 2
},
3: {
id: 3
}
}
**/