https://github.com/dantehemerson/arr2obj
:tada: Converts an array to object, with custom key and value.
https://github.com/dantehemerson/arr2obj
arr2obj arrays node-module package parser tranform typescript-library
Last synced: about 2 months ago
JSON representation
:tada: Converts an array to object, with custom key and value.
- Host: GitHub
- URL: https://github.com/dantehemerson/arr2obj
- Owner: dantehemerson
- License: mit
- Created: 2019-08-21T22:29:35.000Z (almost 7 years ago)
- Default Branch: master
- Last Pushed: 2023-01-04T07:48:34.000Z (over 3 years ago)
- Last Synced: 2025-10-06T12:41:47.732Z (8 months ago)
- Topics: arr2obj, arrays, node-module, package, parser, tranform, typescript-library
- Language: TypeScript
- Homepage:
- Size: 228 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 19
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# arr2obj
[](https://travis-ci.org/dantehemerson/arr2obj)
[](https://github.com/dantehemerson/arr2obj/blob/master/LICENSE)
[](https://www.npmjs.com/package/@dantehemerson/arr2obj)
Converts an array to object, with custom key and value.
## Install
```
npm i @dantehemerson/arr2obj
```
or with yarn:
```
yarn add @dantehemerson/arr2obj
```
## Usage
You can import as follows:
```js
const { arr2obj } = require('@dantehemerson/arr2obj')
```
The function is:
### `arr2obj(array, [options])`
#### Arguments
**`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:
```js
{
key: item => `pre-${item}`,
value: item => item
}
```
If you use Typescript, the interface of `options` is:
```typescript
interface Options {
key?: (item: any) => object | number | string | boolean
value?: (item: any) => object | number | string | boolean
}
```
#### Returns
**`Object`** tranformed.
## Examples
#### Array of basic types:
```js
const result = arr2obj(['a', 'b', 'c'])
// result:
// { a: 'a', b: 'b', c: 'c' }
```
#### Array of objects
```js
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
}
}
**/
```
## Author
[Dante Calderon](https://dantecalderon.dev) - [@dantehemerson](https://github.com/dantehemerson)
## Licence
[MIT](./LICENSE)