Created
December 30, 2012 08:33
-
-
Save lgsunnyvale/4411632 to your computer and use it in GitHub Desktop.
from array to nested
This file contains 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
$(function() { | |
var placeArray = function(array, target) { | |
array.forEach(function(item) { | |
target = placeObj(item, target); | |
}); | |
return target; | |
}; | |
var placeObj = function(obj, target) { | |
if (target.length === 0 ) { | |
return; | |
} | |
for (var i = 0; i < target.length; i++) { | |
if (obj.parentId == target[i].id) { | |
target[i].children.push({ | |
id: obj.id, | |
children: [] | |
}); | |
break; | |
} | |
else { | |
target.forEach(function(t) { | |
placeObj(obj, t.children); | |
}); | |
} | |
} | |
return target; | |
}; | |
console.log(placeObj({id:2,parentId:1}, [{id:0,children:[{id:1, children:[]}]}])); | |
console.log(placeArray([{id:2,parentId:1}, {id:3, parentId:2}, {id:4, parentId:2}], [{id:0,children:[{id:1, children:[]}]}])); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment