;(function (root, factory) {
if (typeof exports === 'object') {
module.exports = factory();
} else if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(factory);
} else {
root.baseExtend = factory();
}
})(this, function() {
// module
return {
/*
usage
* var tree = listToTree(list, {
idKey: 'id',
parentKey: 'parentId',
childrenKey: 'children'
});
*
* */
listToTree:function(data, options) {
options = options || {};
var ID_KEY = options.idKey || 'id';
var PARENT_KEY = options.parentKey || 'parent';
var CHILDREN_KEY = options.childrenKey || 'children';
var tree = [],
childrenOf = {};
var item, id, parentId;
for (var i = 0, length = data.length; i < length; i++) {
item = data[i];
id = item[ID_KEY];
parentId = item[PARENT_KEY] || 0;
// every item may have children
childrenOf[id] = childrenOf[id] || [];
// init its children
item[CHILDREN_KEY] = childrenOf[id];
if (parentId != 0) {
// init its parent's children
childrenOf[parentId] = childrenOf[parentId] || [];
// push it into its parent's children
childrenOf[parentId].push(item);
} else {
tree.push(item);
}
};
return tree;
}
}
})
评论(8)
可以啊
什么
test
sdf
123
1111111
test
test