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

change the value of the key in the current array object react

I have a steate with an array of objects:

const [Value, setValue] = useState([
   { value1: false, value2: false, value3: false },
   { value1: false, value2: false, value3: false },
   { value1: false, value2: false, value3: false }
]);

And using the map method, I render a div for each object:

{Value.map((item, i) => {
    return (
      <div
        key={i}
        onClick={() => {
          setValue((oldArr) => {
            let newArr = [...oldArr];
            newArr[i].value3 = true;
            return newArr;
          });
        }}
      >
        {item.value3 ? 'yes' : 'no'}
      </div>
    );
})}

And then I click to assign the true to the key value3 of the current object.

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

But I can’t figure out how I should assign the false to all other keys value3 from other objects on this click. Exactly, I want to click and get true for current key value3 and all other value3 get false.

Help me pls!

>Solution :

For one thing, this is mutating state:

newArr[i].value3 = true;

Definitely don’t do that. We can solve both this and the issue at hand by projecting these array elements into a new array, setting other values to false and the target value to true. For example:

setValue((oldArr) => oldArr.map((a, x) => ({
  ...a,
  value3: x === i ? true : false
}));

What this does is map over the existing array, constructing new objects which contain all properties of the existing objects and a manual value for value3, which is true if the index of the array matches i and false otherwise.

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