data_by_key
v0.0.1
Published
A set of functions to allow for pulling of data from hierarchical structures using a single key separated.. .useful for templates and the like
Downloads
2
Readme
- Data By Key Module
This module allows reading elements from within multiple levels of a javascript data object by using character separated keys instead of the usual notation.
The motivation for this module was to support template engines, though there could well be other applications.
There are two basic functions in this module and a wrapper class.
Functions
byKey(key, dataObject, separator (optional))
*returns: the element at that the location specified by key
param key is a string containing the nested keys of the desired item in the object..
param dataObject is a javascript object or array.
Key is parsed with the assumption that all the elements in the key are intended to be strings, unless the object at that level in the hierarchy is an array, in which case the key would be parsed into an integer.
param *separator* (optional) specifies which character will separate the nested keys in the string. Default is "."
- example of two ways to return the value at obj["a"]["zero"]:
- byKey("a.zero");
- byKey("a/zero", "/");
The second differs by specifying a separator character other than ".".
setByKey(key, dataObject, value, separator) returns( the original data object ) param key in the same as for byKey function. param dataObject is the same as for byKey function. param value is the value to be set at that location. param separator is the same as for byKey function.
- example of two ways to set the value "19551105" at obj["a"]["one"]:
- setByKey("a.zero", 19551105);
- setByKey("a.zero", 19551105, "/");
KeyedData Class
This class will encapsulate a data object as an instance variable and also a default character separator as an instance variable. It calls the byKey and setByKey functions on this data object.
To create a KeyedData instance:
var keyedData = new KeyedData(dataObject, separator);
To get a value from a KeyedData instance:
var value = keyedData.get("one.interiorkey");
To set a value in a KeyedData instance: keyedData.set("one.interiorkey", "trumanshow");