I have an arbitrarily deep nested array of objects, simplified here as:
interface IComponent {
title: string;
components?: IComponent[];
}
const data: IComponent[] = [
{
title: 'First Component',
components: [
{
title: 'Nested Component 1',
components: [
{
title: 'Child 1 of: Nested Component 1'
},
{
title: 'Child 2 of: Nested Component 1'
},
{
title: 'Child 3 of: Nested Component 1'
}
]
},
{
title: 'Nested Component 2',
components: [
{
title: 'Child of: Nested Component 2'
}
]
}
]
}
];
I have an array of the indexes in this nested array that point to one object to return:
const indexMap: number[] = [0, 0, 2];
Currently, I'm cheating by creating a string to eval as such:
let evalString = 'data';
indexMap.forEach((index: number, iterator: number) => {
if (iterator === 0) {
evalString += `[${ index }]`;
}
else {
evalString += `.components[${ index }]`;
}
});
Resulting in a string such as: data[0].components[0].components[2]
Which works, but I'd like to avoid using eval. I've tried a few variations using .reduce()
but I seem to be stumbling over first getting data[index]
and then accessing the components
value.
Is there a better/simpler/safer way of getting to data[0].components[0].components[2]
given this data structure?
This question: Index an array of arrays with an array of indexes in javascript is similar, but with a different data structure.
This question is also similar: Accessing nested JavaScript objects and arrays by string path but my root object has a slightly different data structure.