Skip to content
Advertisement

Can I set a key-value of a object, a call for a function? If so, how can I call it?

I have an array of objects and for each object I assign an ID and a task to do, as the following;

const Data = [{
        id: 1,
        task: doSomething()
    },
    {
        id: 2,
        task: doSomethingElse()
    },
    {
        id: 3,
        task: doAnotherThing()
    },
    {
        id: 4,
        task: DoYetAnotherThing()
    },
]

I have a for loop which goes over each of the objects in the array and compares it against the wanted id (which is not permanent). When found, I want the program to run it’s task. That’s when I run into problems:

let wantedID = 3
for (const key of Data) {
    if (key.id == wantedID) {
        key.task
    }
}

I thought that if I just mention key.task it would call the function and the program would run the task, as key.task is a call for the function, but it doesn’t work. trying key.task() threw an error, as key.task is not a function..?

How can I fix this?

Thanks!

Advertisement

Answer

Remove the () from the object and add them in the for loop. Also define the functions themselves

const Data = [{
        id: 1,
        task: doSomething
    },
    {
        id: 2,
        task: doSomethingElse
    },
]

let wantedID = 2
for (const key of Data) {
    if (key.id == wantedID) {
        key.task()
    }
}
function doSomething(){
  console.log("doSomething")
}

function doSomethingElse(){
  console.log("doSomethingElse")
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement