0

it's hard to explain, bur lets go on with a example

const exampleProperty = {
    log1: () => {
        console.log('log1')
    },
    log2: () => {
        console.log('log2')
    },
    log3: () => {
        console.log('log3')
    },
    log4: () => {
        console.log('log4')
    }
}
for (let i = 0; i < 4; i++) {
    // now here I want to run all the functions in the example Property
    // I imagined it something like
    exampleProperty.log${i}
    // but this is invalid syntax
}

There might be a real easy answer to this but as I am new i really can't imagine what to do

2 Answers2

1

If you wanted to enumerate every method

const exampleProperty = {
    log1: () => {
        console.log('log1')
    },
    log2: () => {
        console.log('log2')
    },
    log3: () => {
        console.log('log3')
    },
    log4: () => {
        console.log('log4')
    }
}

Object.values(exampleProperty).forEach(p => p())
Jamiec
  • 133,658
  • 13
  • 134
  • 193
0

Working example, using backticks

const exampleProperty = {
    log1: () => {
        console.log('log1')
    },
    log2: () => {
        console.log('log2')
    },
    log3: () => {
        console.log('log3')
    },
    log4: () => {
        console.log('log4')
    }
}
for (let i = 1; i <= 4; i++) {
    // now here I want to run all the functions in the example Property
    // I imagined it something like
    exampleProperty[`log${i}`]();
    // but this is invalid syntax
}
Naren Murali
  • 19,250
  • 3
  • 27
  • 54