Skip to content

Instantly share code, notes, and snippets.

@robertz
Last active January 30, 2025 21:02
Show Gist options
  • Save robertz/8931a39b171034522095176281edc3a6 to your computer and use it in GitHub Desktop.
Save robertz/8931a39b171034522095176281edc3a6 to your computer and use it in GitHub Desktop.
build nested array of objects from a flat array
// https://trycf.com/gist/5276cc942cc493a1e6f42b74b9f93eb0/lucee5?theme=monokai
data = [
{"id": 1, "message": "one", "parent": 0},
{"id": 2, "message": "two", "parent": 1},
{"id": 3, "message": "three", "parent": 2},
{"id": 4, "message": "four", "parent": 3},
{"id": 5, "message": "five", "parent": 4},
{"id": 6, "message": "six", "parent": 5},
{"id": 7, "message": "seven", "parent": 0},
{"id": 8, "message": "eight", "parent": 7},
{"id": 9, "message": "nine", "parent": 8},
{"id": 10, "message": "ten", "parent": 9}
];
out = [];
root = data.filter((msgs) => {
return msgs.parent == 0;
});
root.each((msg) => {
out.append(build(msg))
});
dump(out);
function build(required struct el){
var msg = {
"id": el.id,
"message": el.message,
"children": []
}
var children = data.filter((child) => {
return child.parent == el.id
});
children.each((child) => {
msg.children.append(build(child));
});
return msg;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment