Skip to content

zipToObject

Input two arrays keys and values, and return a plain object where elements of keys serve as keys and elements of values serve as values.

Optional parameters getKey and getValue can be provided to transform elements of the objects into keys and values, respectively.

These can be field paths of getByPath or callback functions.

Added in v0.0.1

Usage

ts
import { zipToObject } from 'parsnip-kit'

zipToObject(['id', 'name', 'skill'], [1, 'Alex', ['Javascript']])
// { id: 1, name: 'Alex', skill: ['Javascript'] }

const users = [{ id: 0, user: 'IAmBot' }, { id: 2, user: 'Alice' }, { id: 5, user: 'Tom' }]
const record = [
  { system: 'Linux', count: 99999, userId: 0 },
  { system: 'Mac OS', count: 10, userId: 2 },
  { system: 'Window', count: 2, userId: 5 },
]
zipToObject(
  users, record, 'user', 'count'
) // { IAmBot: 99999, Alice: 10, Tom: 2 }

zipToObject(
  users, record, item => item.user, item => item.count
) // { IAmBot: 99999, Alice: 10, Tom: 2 }

API

Type Parameter

ArgTypeDescription
TType of elements of array serving as keys
UType of elements of array serving as values

Arguments

ArgTypeOptionalDefaultDescription
keysT[]falseundefinedThe array serving as keys
valuesU[]falseundefinedThe array serving as values
getKeystring | ((item: T, index: number, arr: T[]) => any)trueundefinedTransform array elements into keys
getValuestring | ((item: U, index: number, arr: U[]) => any)trueundefinedTransform array elements into values

Returns

Type
ObjectLike

Reference

ObjectLike