Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

88
Views
Function keep initialising local variable instead of using existing variable

I'm new in javascript and I'm trying to get a bunch of task from different projects from todoist and trying to assign a label for those tasks.

const task_list = {};
for (let id of project_id) {
    api.getTasks({
        projectId: id, filter: "(today | overdue | p1) & !subtask"
    })
        .then((tasks) => { Object.assign(task_list, { id: tasks }); console.log(task_list)})
        .catch((error) => console.log(error))
        
}

for (let id of project_id) {
    console.log(id)
    console.log(task_list.id)
}

This is currently my draft for the code. The console.log in the for loop at the bottom is printing undefined but the console.log behind the Object.assign is able to print out the correct output.

Please help.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You are replacing the id key of task_list object for every iteration , because Object.assign copies the keys and values from an object to the target object which is task_list in your case.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

if you are trying to create a hash table to keep track of all tasks by id

you could mutate the task_list and assign it by id

task_list[id] = tasks

or replace the original task_list using Object.assign

const new_task_list = {}
new_task_list[id] = tasks

task_list = Object.assign(task_list, new_task_list)

or using es6 syntax

Object.assign(task_list,{[id]:tasks})

inside your later loop you can access the task value using the id key

for (let id of project_id) {
    console.log(task_list[id].id)
}

also, the last loop will print an empty object because it will get executed before api.getTasks completed the request, you would need to create an array to save all promises then use

Promise.all(promises).then(() => {
// your loop here
})

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!