'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>)
}
Solution 1:[1]
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);
}
Solution 2:[2]
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'}
})
Solution 3:[3]
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();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Red |
| Solution 2 | R4ncid |
| Solution 3 | Barmar |
