Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

199
Visualizações
add objects to array without overwriting

I have my current code

let array = {};
          array[date] = [
            {
              Name: Name,
              Cell: Cell,
              Age: Age,
              userId: userId,
              Time: time,
              Type: type,
              read: false,
            },
          ];

that uploads to firebase like this enter image description here

but every time i add a new entry for the same date, it overwrites the existing data. I want the data to be add to map "1" etc instead of overwriting the data in map "0"

update: I have tried the following and I am receiving an error. Not sure if I did this correctly, I am still learning.

 let array = {};
          array[date] = [];
          try {
            await firebase
              .firestore()
              .collection("Notifications")
              .doc(`${helper}`)
              .update(
                {
                  array: firebase.firestore.FieldValue.arrayUnion({
                    Name: Name,
                    Cell: Cell,
                    Age: Age,
                    userId: userId,
                    Time: time,
                    Type: type,
                    read: false,
                  }),
                },

                { merge: true }
              );
          } catch (e) {
            alert(e);
            console.log(e);
          }

update with push:

 // at beginning of script
          let array = {};

          // later, when you want to add to it
          if (!array[date]) {
            array[date] = [];
          }
          array[date].push({
            Name: Name,
            Cell: Cell,
            Age: Age,
            userId: userId,
            Time: time,
            Type: type,
            read: false,
          });

    

          try {
            await firebase
              .firestore()
              .collection("Notifications")
              .doc(`${helper}`)
              .set(
                array,

                { merge: true }
              );
          } catch (e) {
            alert(e);
            console.log(e);
          }
        },

Solution:

try {
  await firebase
    .firestore()
    .collection("Notifications")
    .doc(`${helper}`)
    .update({
      [date]: firebase.firestore.FieldValue.arrayUnion({
        Name: Name,
        Cell: Cell,
        Age: Age,
        userId: userId,
        Time: time,
        Type: type,
        read: false,
      }),
    });
} catch (e) {
  alert(e);
  console.log(e);
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Since you set the entire 2022-01-03 field, you are overwriting any existing values in that field.

If you want to merge the new value/object you specify with the existing values in a field use the array-union operator.

about 4 years ago · Juan Pablo Isaza Relatório

0

Use push() to add to an array.

// at beginning of script
let array = {};

// later, when you want to add to it
if (!array[date]) {
  array[date] = [];
}
array[date].push({
  Name: Name,
  Cell: Cell,
  Age: Age,
  userId: userId,
  Time: time,
  Type: type,
  read: false,
});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda