Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

The value in the condition without a variable

I hope to get the result and assign it a new value using such a short entry. I want the result and value to be without creating a variable. How should I do it right?

for example:

let clientOnline =[{num:4},{num:1},{num:3}];
let myValue =clientOnline.find(cli=>cli['num']===4)
if(myValue) myValue['num'] = 0;

What I would like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let clientOnline =[{num:4},{num:1},{num:3}]
if(clientOnline.find(cli=>cli['num']===4)) this['num']=4

I have more experience in languages where variables need to be freed. I know that JS does it on its own. But I really want to control it. I hope it’s possible.

>Solution :

You can find the element in the array and update it in one go

clientOnline.map(c => c.num === 4 ? ({ num: "new_value" }) : c)

Update (addressing your comment)

If you have multiple elements with the same value then you can simply use a for loop and stop whenever you need.

for(let i = 0; i < clientOnline.length; i++) {
  if(clientOnline[i].num === 4) {
    clientOnline[i].num = "new_value"
    break
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading