My collection of objects looks like this:
{ title: "A", parent_id: "root", has_children: true}
{ title: "A1", parent_id: "A", has_children: true}
{ title: "A11", parent_id: "A1", has_children: false}
{ title: "A12", parent_id: "A1", has_children: false}
{ title: "A13", parent_id: "A1", has_children: false}
{ title: "B", parent_id: "root", has_children: true}
{ title: "B1", parent_id: "B", has_children: true}
{ title: "B11", parent_id: "B1", has_children: false}
{ title: "B12", parent_id: "B1", has_children: false}
{ title: "B13", parent_id: "B1", has_children: false}
Each record includes parameters indicating whether it has children and its parent card.
The record with "root" as the parent is considered the top-level card.
Based on the provided data, I would like to transform it into the following format:
[
{
"title": "A",
"children": [
{
"title": "A1",
"children": [
{
"title": "A11"
},
{
"title": "A12"
},
{
"title": "A13."
}
]
}
]
},
{
"title": "B",
"children": [
{
"title": "B1",
"children": [
{
"title": "B11"
},
{
"title": "B12"
},
{
"title": "B13."
}
]
}
]
}
]
I've been attempting to achieve this without success using Meteor and MongoDB.
getUserJSON = function(userId) {
var userJSON = [];
getJSONCards(userId, 'root', userJSON);
}
getJSONCards = function(userId, parent_id, userData) {
var allCards = userCards.find({ $and: [{user_id: userId}, {parent_id: parent_id}]}).fetch();
if (allCards.length > 0) {
allCards.forEach(function(cardInfo) {
var isExist = $.grep(userData, function(e) { return e.content === parent_id; });
if (isExist) {
// Unsure how to add nested cards here
}
});
}
}
I am open to a straightforward JavaScript solution to this problem.