dynamapping
TypeScript icon, indicating that this package has built-in type declarations

1.6.0 • Public • Published

A function that replaces keys from dynamically specified objects within the values for a raw object.

dynamapping

codecov

Version Downloads/week License

Geenee Template

📋 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.

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:

  1. A boolean or a string of a boolean will be converted to a boolean unless it is contained in a larger string
  2. Similar treatment is done for valid number strings or JSON stringifications.

💡 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:

  1. object currently needs to be of depth 1 (no recursion is currently implemented.)
  2. You can currently use one of two mappings: session and answer. (The session object is so named to be generic. The answer object can be useful for an interactive session, for instance using inquirer).
  3. if you set a value in session (or answers) to 'true' or 'false' then dynamapping will assume that you intended the boolean value and will return the boolean true or false 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.

Package Sidebar

Install

npm i dynamapping

Weekly Downloads

3

Version

1.6.0

License

MIT

Unpacked Size

13.7 kB

Total Files

17

Last publish

Collaborators

  • yisroel