As I reach the final stages of completing my JavaScript code for generating an array of JSON formatted objects, I have successfully created a top-level parent along with its corresponding child records.
Now, my task is to add more records to one or more child records. This is where I am encountering some difficulties.
The target data includes a top-level node with "id": 29 and a "children" array beneath it:
[
{
"id": 29,
"field0": "$ALL$",
"field1": 1564.92711931719,
"field2": -171.934775655824,
"field3": -292.877167373888,
"children": [
// Child records here
]
}
]
Next, I have a remaining source array that needs to be linked to its respective parent record mentioned above.
[
{
// Source array items here
}
Using UnderscoreJS library, I can locate each item in the remaining source array, but I need help on how to append them to the parents[] array.
In an update, I have included an _.each() loop which is starting to create the children records; however, there are still some items left in the source array that will eventually become part of the nested hierarchy.
findPar["children"] = thisChild[0];
I believe there could be a more efficient way to achieve this goal.
var findPar;
_.each(rowsNew, function (row) {
// Locate parents array based on id == row.parent condition
findPar = _.findWhere(parents[0].children, { id: row.parent });
if (findPar != undefined) {
if (findPar.children == undefined) {
findPar["children"] = createJsonFromSingleRow(row);
}
else {
findPar.children.push(createJsonFields(row));
}
rowsNew = _.reject(rowsNew, function (rec) { return rec.id == row.id; }); }
});
return newJson = parents;
Thank you for your assistance.
Sincerely, Bob