Learn more  » Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Bower components Debian packages RPM packages NuGet packages

skava / exotic   js

Repository URL to install this package:

Version: 2.0.8 

/ src / types / obj / cast / fromArrayToObj.ts

import isArray from '../../array/check/isArray'
import toKey from '../../attributes/properties/toKey'
import { PairedArrayOf } from '../../array/pairs/Pairs.typings'

/**
 * Converts lists into objects.
 * Pass either
 * 1. a single array of `[key, value]` pairs,
 * 2. or two parallel arrays of the same length -- one of keys, and one of
 *    the corresponding values.
 * Passing by pairs is the reverse of _.pairs.
 * @since 5.0.0-beta.6
 * @memberOf cast
 *
 * @alias fromArrayToObj
 * @alias fromPairs
 *
 * @param  {Array} list list of keys, or of [key, value] pairs
 * @param  {Array} [values] values if not using pairs
 * @return {Object}
 *
 * @see cast/pairs
 *
 * @example
 *  arrayToObj
 */
function arrayToObj<Pair, Values>(
  list: PairedArrayOf<Pair> | any,
  values?: Array<Values>
) {
  const result = {}

  // getLength
  for (let i = 0, length = list.length; i < length; i++) {
    // keys, values
    if (values) {
      result[list[i]] = values[i]
    } else if (isArray(list[i])) {
      // fallback to list as an object as pairs,
      result[list[i][0]] = list[i][1]
    } else {
      // cast key, values-as-keys
      result[toKey(list[i])] = list[i]
    }
  }

  return result
}

export { arrayToObj }
export default arrayToObj