Dealing with an array of nested objects, the goal is to compare values with a flat array and update the property matchFound.
If the parent's matchFound is true, then all its children should inherit this value.
treeData = [{
field: 'make',
name: 'Infiniti',
matchFound: null,
children: [{
field: 'model',
name: 'G50',
matchFound: null,
children: [{
field: 'trim',
name: 'Pure AWD',
matchFound: null,
},
{
field: 'trim',
name: 'Luxe',
matchFound: null,
},
],
},
...
],
},
...
];
The task involves scanning the flatData array to locate the corresponding node in treeData and updating the properties accordingly. For example, { make: "BMW" } - It should update {field: 'make', name: 'BMW', matchFound: true,...}, and all its children.
{ make: "Infiniti", model: "G50", trim: "Luxe" } should only update the matchFound of "Luxe".
The main issue lies in identifying the correct node in treeData using flatData. If altering the structure of flatData can assist in solving the problem, that step can also be taken.
flatData = [{
make: "Infiniti",
model: "G50",
trim: "Luxe"
}, ...]
An attempt was made to convert flatData into the treeData structure but it did not yield the expected results.
[{
field: 'make',
name: 'Infiniti',
matchFound: null,
children: [...],
},
...
];
The proposed solution is far from ideal as there are difficulties in locating the correct node in treeData.
for (const item of this.flatData) {
for (const [key, value] of Object.entries(item)) {
for (let i = 0; i < this.treeData.length; i++) {
if (this.treeData[i].name === `${value}`) {
this.treeData[i].matchFound = true;
if (this.treeData[i].hasOwnProperty('children')) {
this.updateAllChildren(i, this.treeData[i].children);
}
}
}
}
}
// Function to set matchFound true for all children
function updateAllChildren(index, items) {
for (let j = 0; j < items.length; j++) {
this.treeData[index].children[j].matchFound = true;
if (this.treeData[index].children[j].hasOwnProperty('children')) {
for (let k = 0; k < this.treeData[index].children[j].children.length; k++) {
this.treeData[index].children[j].children[k].matchFound = true;
}
}
}
}