1

I have an objects array like this below:

const [categories, setCategory] = useState([
    { text: "a", active: false },
    { text: "b", active: false },
    { text: "c", active: false },
    { text: "d", active: false }
  ]);

and I want to update the active fields to be true. I tried something like this but it doesn't work correctly at all:

  const clearFilters = () => {
    setCategory(categories.map((m) => (m.active = true)));
  };

2 Answers 2

1
const clearFilters = () => {
   setCategory(categories.map((category) => ({...category, active: true})));
};

This must work. ".map" s callback function will be executed for every item of array, and every time will expect from you the new changed item. So you must return the new changed item. In my example above I used ES6 destructuring syntax, if you use ES5 it will be like this.

const clearFilters = () => {
   setCategory(categories.map((category) => ({text: category.text, active: true})));
};

And yes, if you return the object in arrow function right away instead of executing function, you must put it into parentheses, otherwise it will understand it as function body, not object

Sign up to request clarification or add additional context in comments.

1 Comment

If my answer worked, can you mark is as solved? Thanks.
1

Try something like below:-

  const clearFilters = () => {
    const clearedCategories = categories.map(m => {
      m.active = true;
      return m;
    });
    setCategory([...clearedCategories]);
  };

Comments

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.