CalvinTorra

Updating an Object value using .map() and ternary operators


I feel like I have to write these things down otherwise 2 hours of searching Google trying to ask the right question would have been lost.

I’m currently building an app for an Occupational Therapist and we’re implementing a complicated exam where the results are not quite linear.

I know that I’ve done this in the past when working through a Redux tutorial, but I couldn’t remember the exact syntax for mapping over an array of objects, finding the correct object and updating one of it’s values using the spread operator.

The first solution that seemed to be what I was looking for was using React and useState(), which is perfect but….. I felt that I should try to internalise how to do it in VanillaJS as well.

So I threw together a small example to see if I could replicate what I found, save the idea and apply it to the exam later.

This is when I realised that asking the correct question is 80% of the problem for me when exploring programming. It took me around 2 hours of searching to find a similar solution using .map() on an array of objects while using the spread operator.

The first JS solution was using if…else. I don’t mind this, but I felt like it could be more compact and easier to read, so I kept searching.

Now I tried to combine the ternary operator method in React that I found here, but translate it back into VanillaJs, but I could not for the life of me figure out why it wasn’t working. Over and over I tried to find an example only to realise that I should have had two returns within my function [facepalm].

I’m leaving this here in case it helps anybody else.

This is more of a reminder to myself, but for other self-taught Devs like myself that might have forgotten, .map() is iterating over the items within my array called myObj. The items in question happens to be an array of objects.

I’m writing a function called increment which takes two arguments, id and newAge. My intention is to filter the items in my array, find the item that has the id in question and update that item’s age value (in the future that will be a score based on questions in an exam).

return myObj.map((item)) -> The item would refer to each array element that we’re looping over and either manipulating or leaving alone.

Ternary Time:

return item.id === id ? { …item, age: newAge } : item;

This is what I was looking for really. What I’m saying here is for each item in the array, if this item has the id equal to the id I passed into the function do the operation on the left side of the :, OTHERWISE do the operation on the right side of the :.

For the left side, it means we’ve found the item in question so, spread out all the values of that object as normal, BUT change the age to the value passed into the function OTHERWISE just return the item untouched and loop over the next item in the array.