Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

90
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda