Dynamic field access treats field names as runtime strings, allowing application code to read, write, omit, or rename map entries without fixed property syntax. This separates database naming from application-facing JSON conventions. section 10.3
Renaming database results
A query returns title and publication_year, but the application wants bookTitle and publicationYear. Pass that mapping to renameResultKeys instead of rewriting each query or hand-coding each result shape. section 10.3
Listing 10.14 Renaming the keys in SQL results
function renameKeys(map, keyMap) {
return _.reduce(keyMap,
function(res, newKey, oldKey) {
var value = _.get(map, oldKey);
var resWithNewKey = _.set(res, newKey, value);
var resWithoutOldKey = _.omit(resWithNewKey, oldKey);
return resWithoutOldKey;
},
map);
}
function renameResultKeys(results, keyMap) {
return _.map(results, function(result) {
return renameKeys(result, keyMap);
});
}
Inspect the generic implementation: dynamic reads obtain values by old-key strings, dynamic writes create new keys, and omission removes the originals. section 10.3
Listing 10.15 Unit test for renameResultKeys
var listOfMaps = [
{
"title": "7 Habits of Highly Effective People",
"isbn": "978-1982137274",
"publication_year": 1989
},
{
"title": "The Power of Habit",
"isbn": "978-0812981605",
"publication_year": 2012
}
];
var expectedResults = [
{
"bookTitle": "7 Habits of Highly Effective People",
"isbn": "978-1982137274",
"publicationYear": 1989
},
{
"bookTitle": "The Power of Habit",
"isbn": "978-0812981605",
"publicationYear": 2012
}
];
var results = renameResultKeys(listOfMaps,
{"title": "bookTitle",
"publication_year": "publicationYear"});
_.isEqual(expectedResults, results);
Inspect the unit test that verifies renamed keys and preserved values across multiple database-result maps. section 10.3
