Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

117
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!