Skip to content

How to get element of array with string index path

I have an array and I have a path to a specific element.

const str = "[0].subArray[2]"

const arr = [
  { subArray: [1, 2, 3, 4, 5] }, 
  { subArray: [32, 321, 11]}
];

Is it possible somehow to display an element using a string path?

Answer

You could take a dynamic approach for an length of the path.

function getValue(object, path) {
    return path
        .replace(/[/g, '.')
        .replace(/]/g, '')
        .split('.')
        .filter(Boolean)
        .reduce((o, k) => (o || {})[k], object);
}

console.log(getValue([{ subArray: [1, 2, 3, 4, 5] }, { subArray: [32, 321, 11] }], "[0].subArray[2]"));