Access objects by a combination of an object and two paths

I would like to combine an object, a path in a variable and a path, something like explained in but with 3 "parts".

Here is minimal reproducible example:
I want the combine() function to print selector[0].children[foo].textContent or selector[0].children[foo].children[0].textContent depending on bar value.

const selector = document.getElementsByClassName('main')
const foo = 0
let bar = ''

const toggle = () => {
  if (bar === '') bar = '.children[0]'
  else bar = ''

const test = () => {
  console.log(combine('selector[0].children[foo]', bar, '.textContent'))
  //I want a function like combine() that will print 'selector[0].children[foo].textContent' or 'selector[0].children[foo].children[0].textContent' depending on bar value.
<div class='main'>
  <button onclick='toggle()'>toggle</button>
  <button onclick='test()'>test</button>

I have a class that is returning multiple similar properties (10). My constructor inputs a value that can be used to determine something like bar in the minimal example. Each property by just changing something like bar in the minimal example can have the intended output.
I want something like this to be able to switch between different cases without having to write a massive switch for each bar cases so a lot of code duplication.

22 thoughts on “Access objects by a combination of an object and two paths”

Leave a Comment