Skip to content

Instantly share code, notes, and snippets.

@lgsunnyvale
Created December 30, 2012 08:33
Show Gist options
  • Save lgsunnyvale/4411632 to your computer and use it in GitHub Desktop.
Save lgsunnyvale/4411632 to your computer and use it in GitHub Desktop.
from array to nested
$(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