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

211
Visualizações
How to stop adding duplicate data to Array in react.js

I followed the approach as the answer in this question suggested The issue is that I want to construct an Array using setState and I dont; want to add duplicate data.

here is the sample data

const data = [
  {
    parentId: '1',
    userChoice: 'NO',
    child: []
  },
  {
    parentId: '2',
    userChoice: 'NO',
    child: []
  },
}

I'm catching the parentId from question.id from user input. If there is the same question then I don't want to concat into the array.

This is how I'm trying.

const [data, setData] = useState([]) // state

function arrayHandler(question) {
    const hasParentId = data.find((parentId) => question.id === parentId)
    // concat if array do not have any question with same id. 
    if (!hasParentId) {
      setData((data) => data.concat({ parentId: question.id, userChoice: 'NO', child: [] }))
    }
}

But this is not working, How can I fix this ?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can check if any of the elements in the data have a matching ID using Array.some and if not then you can use concat or just the spread operator to add the new object to the existing data.

function arrayHandler(question) {
  if (!data.some((d) => question.id === d.parentId)) {
    setData((data) => [...data, { parentId: question.id, userChoice: "NO", child: [] }]);
  }
}
about 4 years ago · Juan Pablo Isaza Relatório

0

I think that now it shold work

function arrayHandler(question) {
const hasParentId = data.find((object) => question.id === object.parentId)
// concat if array do not have any question with same id. 
if (!hasParentId) {
  setData((data) => data.concat({ parentId: question.id, userChoice: 'NO', child: [] }))
}

}

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