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

118
Visualizações
How to prevent keep add string to the object in JavaScript?

When click on run button each time Mi string adding how to prevent Result : 1000MiMi Expected result multiple time click : 1000Mi

function App() {
      let memory = [{size:1000}]
      const handleSubmit = () =>{
        memory.map((item) => {
          const manju =  item.size + 'Mi'
          item.size = manju 
          return item
        })
        console.log(memory)
      }
      return (<div>
    <button onClick={handleSubmit}>Run</button>
        </div>)
    }
about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

If your trying to prevent item.size from repeatedly adding 'Mi' onto the end, trying using the .endsWith() method.

const handleSubmit = () => {
    memory.map((item) => {
      if (!(item.size+"").endsWith("Mi")) {
          const manju =  item.size + 'Mi';
      }
      item.size = manju;
      return item;
    });
    console.log(memory);
  }
about 4 years ago · Santiago Trujillo Relatório

0

your problem is here

memory.map((item) => {
          const manju =  item.size + 'Mi'
          item.size = manju 
          return item
        })

you are overwriting the value of item

instead you have to return a new value

like this

memory.map((item) => {
   return {size: item.size + 'Mi'}
})
about 4 years ago · Santiago Trujillo Relatório

0

Since you're not using the result of map() for anything, you should use forEach() instead.

To prevent multiple Mi suffixes, check if it has already been added.

const handleSubmit = () => {
  memory.forEach((item) => {
    if (!(item.size + "").endsWith("Mi")) {
      item.size += 'Mi';
    }
  });
  console.log(memory);
}

const memory = [{size: 1000}]
handleSubmit();
memory.push({size: 500});
handleSubmit();

about 4 years ago · Santiago Trujillo 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