UNPKG

parse-js

Version:

Utility library for object structure conversion.

55 lines (42 loc) 1.23 kB
'use strict'; var _each = require('lodash/each'); var _transform = require('../lib/transform'); var _isPlainObject = require('lodash/isPlainObject'); function GroupTransformer(regex, key, index) { if (!(this instanceof GroupTransformer)) { return this.transform(new GroupTransformer(regex, key, index)); } this._regex = regex; this._key = key; this._index = index; } GroupTransformer.prototype.match = function (key) { this._regex.lastIndex = 0; return this._regex.exec(key); }; GroupTransformer.prototype.parse = function (source) { var _this = this; return _transform(source, function (result, value, key) { var match = _this.match(key); if (!match) { result[key] = value; return; } var newKey = match[_this._key]; var index = match[_this._index]; if (!result[newKey]) result[newKey] = {}; result[newKey][index] = value; }, {}); }; GroupTransformer.prototype.reverse = function (source) { return _transform(source, function (result, value, key) { if (!_isPlainObject(value)) { result[key] = value; return; } _each(value, function (v, idx) { result[key + idx] = v; }); }); }; module.exports = GroupTransformer;