I have an array and I have a path to a specific element.
JavaScript
x
7
1
const str = "[0].subArray[2]"
2
3
const arr = [
4
{ subArray: [1, 2, 3, 4, 5] },
5
{ subArray: [32, 321, 11]}
6
];
7
Is it possible somehow to display an element using a string path?
Advertisement
Answer
You could take a dynamic approach for an length of the path.
JavaScript
1
10
10
1
function getValue(object, path) {
2
return path
3
.replace(/[/g, '.')
4
.replace(/]/g, '')
5
.split('.')
6
.filter(Boolean)
7
.reduce((o, k) => (o || {})[k], object);
8
}
9
10
console.log(getValue([{ subArray: [1, 2, 3, 4, 5] }, { subArray: [32, 321, 11] }], "[0].subArray[2]"));