@juliancoleman/index-by-key
v0.0.1
Published
Converts an array of objects into an object of objects with a given predicate.
Downloads
3
Readme
Index By Key
A curried function using Ramda that transforms an array of objects into an object of objects, where the key is the key specified and the value is the rest of the object. The function will return a new object and will not mutate or destroy the original array.
Install
yarn
yarn add @juliancoleman/index-by-key
npm
npm i -S @juliancoleman/index-by-key
Setup
This package provides the single function mentioned above.
You can specify the key on require
, or you can specify a
key to indexBy
later on.
// initialize without specified key
const indexByKey = require("@juliancoleman/index-by-key");
// initialize with specified key at require
const indexById = require("@juliancoleman/index-by-key")("id");
// initialize with specified key later
const indexByFirstName = indexByKey("first_name");
Once required and a key is specified, you can then call the function on your data to see the transformation. Again, the function will return a new object and will not mutate or destroy the original array.
Below is an example use on a Promise
object returned by
an asynchronous database call:
const indexByKey = require("@juliancoleman/index-by-key");
const { getUsers } = appRequire("path/to/API");
(async () => {
const indexById = indexByKey("id");
const users = await getUsers();
/*
Example `users`
[ { "id": 1,
"first_name": "Julian",
"last_name": "Coleman",
"email_address": "[email protected]" },
{ "id": 2,
"first_name": "Bob",
"last_name": "Sagget",
"email_address": "[email protected]" } ]
*/
if (!users) {
throw new Error("Unable to retrieve users");
}
return indexById(users);
})();
/*
results in the following output
{ "1": { "first_name": "Julian",
"last_name": "Coleman",
"email_address": "[email protected]"
},
"2": { "first_name": "Bob",
"last_name": "Sagget",
"email_address": "[email protected]" } }
*/
Alternatively, this same thing can be achieved by doing the following:
API.getUsers().then(indexByKey("id"));