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

258
Visualizações
Update nested array ES6, JavaScript

I have the following array of objects:

[{
  idChatPublic: "1",
  message: "hello",
  chatLike: [{
    id: "1",
    idChatPublic: "1"
  }]
}]

What I want is simply add a new object into chatLike array. Here is my attempt, but it doesn't seem to be working whats wrong with this piece of code?

async function sendLike(messageId: string) {
  const newLike = {
    idChatPublic: messageId,
  }

  mutateMessages(
    (data) => {
      console.log(data) // returns the array I want to update
      data.map((message) => {
        if (message.idChatPublic === messageId) {
          console.log(message.chatLike) // returns the array inside the object I want to update
          return {
            ...message,
            chatLike: [...message.chatLike, newLike]
          }
        } else {
          return message
        }
      })
    }
  )
}
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

Probably, you have to create const with new array and return it:

const newData = data.map((message) => {
  if (message.idChatPublic === messageId) {
    console.log(message.chatLike) // returns the array inside the object I want to update
    return {
      ...message,
      chatLike: [...message.chatLike, newLike]
    }
  } else {
    return message
  }
});

return newData;
about 4 years ago · Juan Pablo Isaza Relatório

0

You don't need map(). I think you can do that like this:

async function sendLike(messageId: string) {

 const newLike = {
   idChatPublic: messageId,
 };
 
 mutateMessages((data) => {
   data.forEach((message) => {
     if (message.idChatPublic === messageId) {
       message.chatLike.push(newLike);
     }
   }
 });
 
}

Loop throw your objects array with forEach() and if the id will match you can update chatLike array with push() to add a new newLike object.

about 4 years ago · Juan Pablo Isaza Relatório

0

const data = [
  {
    idChatPublic: "1",
    message: "hello",
    chatLike: [
      {
        id: "1",
        idChatPublic: "1",
      },
    ],
  },
];

function updateChatLike() {
  return data.map((d) => {
    return {
      ...d,
      chatLike: [
        ...d.chatLike,
        {
          id: 2,
          idChatPublic: "2",
        },
      ],
    };
  });
}

console.log(JSON.stringify(updateChatLike(), null, 4));

I have used JSON.stringify() to log complete nested object

Output

[
    {
        "idChatPublic": "1",
        "message": "hello",
        "chatLike": [
            {
                "id": "1",
                "idChatPublic": "1"
            },
            {
                "id": 2,
                "idChatPublic": "2"
            }
        ]
    }
]
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