Recurses through a JSON-like object and transforms its primitive values. Effectively applies array.map() to each nested array and _.mapValues() to each nested object.
Install via npm:
npm install --save deep-mapSuppose we have an object containing some nested template strings:
const templateObject = {
name: '<%- name %>',
email: '<%- email %>',
keywords: [
'<%- keyword1 %>',
'<%- keyword2 %>'
],
hobbies: {
primary: '<%- hobby1 %>',
secondary: '<%- hobby2 %>'
}
};And we want to fill it with the following data:
const data = {
name: 'Samuel Johnson',
email: 'sam.johnson@dictionary.com',
keyword1: 'dictionary',
keyword2: 'lexicography',
hobby1: 'writing',
hobby2: 'torying',
};We can use deepMap like so:
const deepMap = require('deep-map');
const template = require('lodash/template');
const fs = require('fs');
let result = deepMap(templateObject, (value) => {
return template(value)(data);
});
fs.writeFileSync('johnson.json', JSON.stringify(result, null, 2));And here is the result:
{
"name": "Samuel Johnson",
"email": "sam.johnson@dictionary.com",
"keywords": [
"dictionary",
"lexicography"
],
"hobbies": {
"primary": "writing",
"secondary": "torying"
}Performs a transformation on each primitive value in an object or array. Properties and indices are visited recursively, so nested primitives will be transformed. By default, a new object is returned without modifying the original or any of its nested objects.
object|array
The object to iterate over. This may be an object or an array, and may contain nested objects and/or arrays.
function
The function to call for each primitive value. The return value of the function determines the transformed value. The function is invoked with two arguments:
-
value: The primitive value being transformed.
-
key/index: The name of the key at the present node in the case of an object, or the index value in the case of an array.
object (optional)
An options object. The following options are accepted:
-
thisArg: Set the
thiscontext withintransformFn. -
inPlace: Mutate the object passed-in rather than returning a new object. Nested objects are also transformed in-place.
object|array
Returns a new object, unless the inPlace option is set, in which case the
old object is returned transformed.
Copyright © 2016 Akim McMath. Licensed under the MIT License.