Skip to content

Commit c3a0a20

Browse files
committed
Lib: Add method for converting a string path to a nested object
1 parent 049b3a9 commit c3a0a20

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

src/lib/index.js

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -486,3 +486,58 @@ lib.setTranslate = function(element, x, y) {
486486
lib.isIE = function() {
487487
return typeof window.navigator.msSaveBlob !== 'undefined';
488488
};
489+
490+
491+
/**
492+
* Converts a string path to an object.
493+
*
494+
* When given a string containing an array element, it will create a `null`
495+
* filled array of the given size.
496+
*
497+
* @example
498+
* lib.toObject('nested.test[2].path', 'value');
499+
* // returns { nested: { test: [null, null, { path: 'value' }]}
500+
*
501+
* @param {string} path to nested value
502+
* @param {*} any value to be set
503+
*
504+
* @return {Object} the constructed object with a full nested path
505+
*/
506+
lib.toObject = function(path, value) {
507+
var keys = path.split('.'),
508+
tmpObj,
509+
obj = tmpObj = {};
510+
511+
for(var i = 0; i < keys.length; i++) {
512+
var key = keys[i];
513+
var el = null;
514+
515+
var parts = keys[i].match(/(.*)\[([0-9]+)\]/);
516+
517+
if(parts) {
518+
key = parts[1];
519+
el = parts[2];
520+
521+
tmpObj = tmpObj[key] = [];
522+
523+
if(i === keys.length - 1) {
524+
tmpObj[el] = value;
525+
} else {
526+
tmpObj[el] = {};
527+
}
528+
529+
tmpObj = tmpObj[el];
530+
} else {
531+
532+
if(i === keys.length - 1) {
533+
tmpObj[key] = value;
534+
} else {
535+
tmpObj[key] = {};
536+
}
537+
538+
tmpObj = tmpObj[key];
539+
}
540+
}
541+
542+
return obj;
543+
};

0 commit comments

Comments
 (0)