dynamapping
v1.6.0
Published
replaces keys dynamically within the values for a raw, flat object
Downloads
20
Maintainers
Readme
A function that replaces keys from dynamically specified objects within the values for a raw object.
:clipboard: Why
You may want to update objects retrieved from a static source (such as a file) using a session with dynamically set values. It's a pain to set up the logic of mapping through session data and calling replace.
:white_check_mark: What
A single function that you can pass in a flat object to and replace strings in the object values with your session values.
Your replacements (the values in your session
object) can include a string, a number, a boolean, or a JSON-stringified object. dynomapping
will determine the intended type as follows:
- A boolean or a string of a boolean will be converted to a boolean unless it is contained in a larger string
- Similar treatment is done for valid number strings or JSON stringifications.
:bulb: How
Include the function:
npm i dynamapping
You can insert into the values for keys of a given object a string in the form __session.<key>__
. Then, dynamically set the session
object to have a value that will be replaced when you call dynamapping
. For instance,
const dynamapping = require('dynamapping')
const session = {
userName: 'Filbert'
}
let obj = {
hello: 'hi __session.userName__'
};
obj = dynamapping( obj, session, {})
// obj will be set to { hello: 'hi Filbert' }
Notes:
object
currently needs to be of depth 1 (no recursion is currently implemented.)- You can currently use one of two mappings:
session
andanswer
. (Thesession
object is so named to be generic. Theanswer
object can be useful for an interactive session, for instance using inquirer). - if you set a value in
session
(oranswers
) to'true'
or'false'
thendynamapping
will assume that you intended the boolean value and will return the booleantrue
orfalse
respectively. For instance:
const obj = {
testCase: '__session.isTrue__'
};
const sessionObj = {
userName: 'Filbert',
isTrue: 'false'
}
obj replaceGlobalValuesInObject(obj, sessionObj, ansObj)
// obj = {testCase: false} rather than {testCase: 'false'}
But if it's embedded within a larger string, it will remain a string e.g. 'it is __session.isTrue__ now!
4.Numbers are treated the same way. If you have a key set to a single number, then it will remain a number.