Javascript: Manipulating a list of lists

Viewed 86

Let's say I have the following:

const tasks = [
    ["Task 1", (() => console.log(123))],
    ["Task 2", (() =>console.log(456))]
];

Is there a way of expressing this:

tasks.forEach( t => {
        console.log(`running ! ${t[0]}`);
        t[1]();
    }
)

in a form resembling this:

tasks.forEach( (taskName, f) => {
        console.log(`running ! ${f}`);
        f();
    }
)

Sadly with the (x, i) syntax, i gives me the index of the items in the list and I cannot get it to refer to the function. I also tried using the [..., ] syntax without luck

1 Answers

You Can destructure the element as you iterate though the array...

tasks.forEach( ([taskName, f]) => {
        console.log(`running ! ${taskName}`);
        f();
    }
)

returns...

"running ! Task 1"
123
"running ! Task 2"
456
Related