1.1.0 • Published 7 years ago
keys-of v1.1.0
keys-of
Returns the keys/indexes at which the specified value is located in a collection.
It’s like Array.prototype.indexOf() except it works on Maps/Objects/etc. and returns all of the keys/indexes, not just the first one.
Installation
Requires Node.js 8.3.0 or above.
npm i keys-ofAPI
The module exports a keysOf() function that has one other function attached to it as a method: keysOf.any().
keysOf()
Parameters
- Bindable:
c(Array, Iterator, Object, Map, Set, string, or Typed Array) valueToFind(any): The value whose corresponding keys or indexes you want to locate.- Optional: Object argument:
arrays/maps/sets(arrays of classes/strings): Arrays of classes and/or string names of classes that should be treated as equivalent toArray/Map/Set(respectively).compareAs(function): A callback that accepts a single existing value from the collection and transforms it before it is compared.compareBy(any): If set, each existing value in the collection is assumed to be a subcollection, and the value in each subcollection corresponding to thecompareBykey will be compared tovalueToFind. Only applies ifcompareAsis not set. IfcompareByis an array, it is assumed to be a chain of nested keys.compareByOptions(object): An options argument for the kget module, which is used whencompareByis set.inObj(boolean): Whether or not to search inherited properties ifcis an Object (i.e. not another recognized type). Defaults tofalse.loose(boolean): Whether or not to identify values loosely (as defined bylooselyEquals). Defaults tofalse.looselyEquals(function): A callback that accepts two values and returnstrueif they are to be considered equivalent orfalseotherwise. This argument is only used iflooseistrue. If omitted, the default behavior will, among other things, consider arrays/objects to be equal if they have the same entries.reflectObj(boolean): Whether or not to use reflection to search non-enumerable Object property values. Only takes effect ifcis an Object (i.e. not another recognized type). Defaults tofalse.
Return Value
An array of keys or numeric indexes (depending on the collection type).
Example
const keysOf = require('keys-of')
const obj = {
a: 1,
b: 2,
c: 2,
d: {},
e: {},
}
keysOf(obj, 1) // ['a']
keysOf(obj, 2) // ['b', 'c']
keysOf(obj, {}) // []
keysOf(obj, {}, {loose: true}) // ['d', 'e']keysOf.any()
Use this function to find the keys that correspond to any of the given values. The signature is the same as the main function except that the second parameter is called valuesToFind and takes an iterable (such as an array or string).
Example
const keysOf = require('keys-of')
const obj = {
a: 1,
b: 2,
c: 2,
d: {},
e: {},
}
keysOf.any(obj, [1, 2]) // ['a', 'b', 'c']
keysOf.any(obj, [1, {}], {loose: true}) // ['a', 'd', 'e']Related
- key-of: Same as this module, except it only returns the first key or index.