Tengo projects de variables de estado que deberían almacenar un diccionario de matrices, donde la clave es la identificación de la organización propietaria del proyecto, y la matriz consta de objetos que almacenan información sobre el proyecto. Por ejemplo:
{ orgId123: [ project1: { name: "my cool project", status: "submitted" }, projectAwesome: { name: "Stan's project", status: "draft" } ], orgUSA: [ newProj234: { name: "another great project", status: "submitted" } ] } Intento obtener una lista de todos los ID de organización usando Objects.keys(projects) , sin embargo, eso devuelve una matriz vacía.
Sospecho que de alguna manera la variable de mis projects está mal estructurada. Cuando console.log . registro el contenido de los projects , obtengo:
Observe cómo el objeto de nivel raíz dice solo {} .
Cuando traté de recrear el aspecto que debería tener la variable de projects y lo registré, vi un resultado ligeramente diferente:
En este objeto creado manualmente, el objeto de nivel raíz se muestra como {orgId1}: Array(1) en lugar del {} mostrado anteriormente (en el objeto real).
¿Qué dice esto acerca de cómo está estructurado el objeto y por qué no puedo obtener una lista de claves del primer objeto usando Object.keys() ?
Por contexto, creo la variable original usando el siguiente código:
async function fetchProjects() { // Load list of organisations that the user is a member of const organisationsSnapshot = await getDocs(query( collection(db, 'organisations'), where(`members.${user.uid}`, '!=', null) )) const organisations = organisationsSnapshot.docs.map(organisationSnap => ({ ...organisationSnap.data(), id: organisationSnap.id })) // Load list of projects for each organisation the user is a member of const projectsDict = {} organisations.forEach(async (organisation) => { const projectsQuery = query(collection(db, `organisations/${organisation.id}/projects`)) const projectsSnap = await getDocs(projectsQuery) projectsDict[organisation.id] = projectsSnap.docs.map(projectSnap => ({ ...projectSnap.data(), id: projectSnap.id })) }) setProjects(projectsDict) }No puede tener una matriz de key:value s. Debes envolverlo en {} .
[ key1: value1, key2: value2, ] //Unexpected Token [ { key1: value1 }, { key2: value2 }, ] //Good to goAsí que en lugar de:
{ orgId123: [ project1: { name: "my cool project", status: "submitted" }, projectAwesome: { name: "Stan's project", status: "draft" } ], orgUSA: [ newProj234: { name: "another great project", status: "submitted" } ] }Deberías:
{ orgId123: [ { project1: { name: "my cool project", status: "submitted" } }, { projectAwesome: { name: "Stan's project", status: "draft" } } ], orgUSA: [ { newProj234: { name: "another great project", status: "submitted" } } ] }O
{ orgId123: { project1: { name: "my cool project", status: "submitted" }, projectAwesome: { name: "Stan's project", status: "draft" } }, orgUSA: { newProj234: { name: "another great project", status: "submitted" } } } Honestamente, estructuraría sus projects de la siguiente manera:
const organisations = [{ orgId: "orgId123", projects: [{ projectId: "project1", name: "my cool project", status: "submitted" }, { projectId: "projectAwesome", name: "Stan's project", status: "draft" }] }, { orgId: "orgUSA", projects: [{ projectId: "newProj234", name: "another great project", status: "submitted" }] } ] //This way, organisations is an array of organisations, //which is an object that has orgId, projects which is an array of its projects. //It will be much more intuitive to work with while iterating over it. //Such as if you need to display all the orgIds, console.log("Organisation IDs:") for (const org of organisations) { console.log(org.orgId) } console.log("================="); //If you need all project IDs and names: console.log("Projects:") for (const org of organisations) { console.log(`Organisation ${org.orgId} has the following projects:`) for (const proj of org.projects) { console.log(`Project ID ${proj.projectId}: ${proj.name}`) } console.log("================="); } console.log("=================");