Created
December 14, 2017 12:01
-
-
Save yuanoook/3caf7c9bed4cbd2c024485696c461adf to your computer and use it in GitHub Desktop.
flattenTreeByChildren & makeTreeWithParentId
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var util = { | |
i: 0, | |
uuid: function() {return this.i++}, | |
copyObj: function(obj) { | |
var result = Array.isArray(obj) ? [] : {}; | |
for (var key in obj) result[key] = obj[key]; | |
return result; | |
} | |
}; | |
function flattenTreeByChildren(data, parentId) { | |
var result = data.map(function(item) { | |
var result = util.copyObj(item); | |
result.children = null; | |
result.parentId = parentId; | |
return result; | |
}); | |
for (var index in data) { | |
if ( | |
data[index] | |
&& data[index].children | |
&& data[index].children.length | |
) { | |
result = result.concat(flattenTreeByChildren(data[index].children, data[index].id)) | |
} | |
} | |
return result; | |
} | |
function makeTreeWithParentId(data) { | |
var result = []; | |
var getItemById = function (data, id) { | |
for (var index in data) { | |
if (data[index] && data[index].id === id) { | |
return data[index] | |
} | |
} | |
}; | |
data.forEach(function(item) { | |
if (!item.parentId) { | |
result.push(item); | |
return; | |
} | |
var parentItem = getItemById(data, item.parentId); | |
parentItem.children = parentItem.children || []; | |
parentItem.children.push(item); | |
}); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment