Transform objects from one structure to another
var xform = require('xform');
var getDeep = xform({
foo: xform.exclude({
bar: {
baz: xform.memo('deep')
}
}),
value: xform.memoValue('deep')
});
console.log(getDeep({
foo: {
bar: {
baz: 'deep value'
}
}
}));
// { value: 'deep value' }
npm install xform --save
Create an object parsing function by feeding a template object to xform
:
var parser = xform(template);
The template is a plain object that represents the object structure you're expecting to receive. Values are pulled from the source object through node-parsing methods on the template:
var template = {
example: xform.value() // Copies value as-is
};
The resulting parser is a function that accepts a source object and returns a transformed object:
var template = {
example: xform.value()
};
const parser = xform(template);
const transformed = parser({
example: 'value'
});
A node-parsing method is simply a function that receives four arguments: value
, result
, key
, and data
.
It's up to the node parser to set a value on the result
object:
function nodeParser(value, result, key) {
result[key] = value;
}
var template = {
example: nodeParser
};
The data
argument is a Map
that's shared by every parser.
Since it's shared, it's possible to clobber other parsers' data, so you should namespace your keys:
data.set('myParser.' + key, value);
xform.value([default])
Simply returns a value as-is.
If the source value is undefined
then default
is returned.
xform.memo(key)
Saves a value for later retrieval.
xform.memoValue(key)
Returns value previously saved by memo
.
xform.exclude(template)
Continues parsing template
but does nothing with the result.
Really only useful if you're using something like memo
in template
.
xform.path(expression, [template])
Performs a JSONPath query and returns the first value.
Passing a second template will traverse the result.