I have the following data that i need to iterate over.
I have came up with the following raw solution to loop through and get my needed data, not sure if this is the most optimal way of doing so, is there any way to speed this up or just to improve the solution?
Object.entries(data[0]).forEach(([key, value]) => {
for (const [key, test] of Object.entries(value)) {
for (const [key, properties] of Object.entries(test.properties)) {
for (const [keys, prop] of Object.entries(properties)) {
console.log(prop);
}
}
for (const [bestkeys, provisions] of Object.entries(test.provisions)) {
//console.log(provisions);
}
}
});
If there is a specific pattern that you need to follow, then explicitly stating your pattern is usually the best way to go, especially for a less complex pattern such as this. I re-wrote your example but using .values instead of .entries because you only used the values.
Object.values(data[0]).forEach(val => {
Object.values(val).forEach(test => {
Object.values(test).forEach(property => {
Object.values(property).forEach(prop => {
console.log(prop);
});
});
Object.values(test.provisions).forEach(provisions => {
console.log(provisions);
});
});
});
However, if you only need to traverse all the branches and log all the deepest level of values, you could use recursive logic as well. i.e.
function logDeepestNestedValue(obj) {
if (typeof obj === "object") {
const values = Object.values(obj);
values.forEach(logDeepestNestedValue);
} else {
console.log(obj);
}
}
logDeepestNestedValues(data[0]);
Looking at your image I noticed that test.provisions might be an array and not an object, in which case you would not want to call Object.values on it, instead you can just use .forEach or directly a for of loop to log things there.