Convert a nested plain JavaScript object into a normalized object without any configuration. Use this library to create { key -> value } maps.
This is especially useful for pre processing JSON responses as it keeps primitive values such as integers and strings intact.
Installation
npm i --save uncover
Usage
This module was created for use in Flux or Redux. If you don't use these libraries and you just want to create key maps you can scroll down for the detailed example.
An action can use this module to first normalize a nested object like so:
import uncover from 'uncover';
export function showBookInformation (id) {
getJSON(`/api/books/${id}`)
.then(json => {
dispatch({
type: 'RECEIVE_BOOK_INFO',
entities: uncover(json, 'book')
})
})
}
Now the reducers or stores can simply check for a result before actually performing the default changes
import { toMap } from 'uncover';
export function (state = {}, action) {
var map = toMap(action.entities, 'books');
if (map) return Object.assign({}, state, map);
switch (action.type) {
default:
return state;
}
}
That's all! No further configuration needed.
For more options like parsing results, creating initial data or integration with the Immutable library you can see this page.
Detailed example
Let's start with our nested value
import uncover from 'uncover';
var results = uncover({
"id": 1,
"name": "Jungle Book",
"keywords": [
"test",
"..."
],
"animals": [
{
"id": 1,
"bookId": 1,
"name": "Bear",
"character": {
"id": 1,
"animalId": 1,
"name": "Baloo"
}
},
{
"id": 2,
"bookId": 1,
"name": "Wolf",
"characters": [
{
"id": 2,
"animalId": 2,
"name": "Akela"
},
{
"id": 3,
"animalId": 2,
"name": "Rama"
}
]
}
]
}, "book");
After calling the uncover
function the value of results
will be:
{
"books": [
{
"id": 1,
"name": "Jungle Book",
"keywords": [
"test",
"..."
]
}
],
"animals": [
{
"id": 1,
"bookId": 1,
"name": "Bear"
},
{
"id": 2,
"bookId": 1,
"name": "Wolf"
}
],
"characters": [
{
"id": 1,
"animalId": 1,
"name": "Baloo"
},
{
"id": 2,
"animalId": 2,
"name": "Akela"
},
{
"id": 3,
"animalId": 2,
"name": "Rama"
}
]
}
Let's process this result further to get a { key -> value } map of the characters
import { toMap } from 'uncover';
results = toMap(results, 'characters',
(map, item) => {
map[item.id] = item
},
{}
)
The value results
now contains the following map:
{
"1": {
"id": 1,
"animalId": 1,
"name": "Baloo"
},
"2": {
"id": 2,
"animalId": 2,
"name": "Akela"
},
"3": {
"id": 3,
"animalId": 2,
"name": "Rama"
}
}