0

I have an array of users and want to set age = 0 if there´s no age present

const [users, setUsers] = useState([{name: 'john', age: 40}, {name: 'mary'}, {name: 'mike'}])

how can I do this? (I don´t have access to the database to set all users age to 0 if there´s no age set)

0

2 Answers 2

4

You should do:

setUsers(users.map(user => ({...user, age: user.age || 0})))
Sign up to request clarification or add additional context in comments.

Comments

3

I think this is will help.

const users = [{name: 'john', age: 40}, {name: 'mary'}, {name: 'mike'}]
users.map(user => {
  if (user.age === undefined) user.age = 0;
  return user;
});

setUsers(users);

5 Comments

If you're not using the new array returned by map, you might as well use forEach
Thank's for your suggestion! @Phil
I mean, there's nothing wrong with using .map() for this but it's not exactly fit-for-purpose
I´m now confused with the difference between both methods. forEach doesn´t modify the original array?
That's the point, forEach modifies the original array. Map ca do the same, as in the example, but the semantics is that it will return a new array. This means that people, looking at map, will expect the returned object to be used.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.