Skip to content

Instantly share code, notes, and snippets.

@sod
Created July 10, 2015 07:54
Show Gist options
  • Save sod/6fe9dd219f6b5e6b8d1a to your computer and use it in GitHub Desktop.
Save sod/6fe9dd219f6b5e6b8d1a to your computer and use it in GitHub Desktop.
var categoryExport = ``;
var lineRx = /^(\t*)(\d+) (.+)$/;
var toSlug = function(label) {
return String(label).replace('&', 'und').replace(/[^a-z0-9]/ig, '-');
};
var toCategoryObject = function(category) {
category = lineRx.exec(category);
return {
level: category[1].length,
id: +category[2],
label: category[3],
slug: toSlug(category[3])
};
};
var addParentId = function() {
var previous = { level: -1 };
var levels = [];
return function(category) {
var array;
if(category.level > previous.level) {
array = [];
levels.push(array);
} else {
array = levels[category.level];
levels.length = category.level + 1;
}
array.push(category);
category.parentId = ((levels[levels.length - 2] || []).slice(-1)[0] || {}).id || 0;
previous = category;
};
};
var categories = categoryExport.split('\n');
categories = categories.map(toCategoryObject);
categories.forEach(addParentId());
JSON.stringify(categories, 2, ' ');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment