Skip to content
Advertisement

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?

Advertisement

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]"));
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement