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>)
}
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);
}
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'}
})
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();